
package com.joysuch.wwyt.monitoringcenter.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.gson.Gson;
import com.joysuch.wwyt.api.dataaccess.OrientationDataSyncService;
import com.joysuch.wwyt.api.dataaccess.bean.OrientationSearchBean;
import com.joysuch.wwyt.bp.bean.BpStoreHouseAddBean;
import com.joysuch.wwyt.bp.bean.BpSystemVideoAddBean;
import com.joysuch.wwyt.bp.entity.*;
import com.joysuch.wwyt.bp.entity.contractor.BpContractorStaff;
import com.joysuch.wwyt.bp.entity.dsl.QBpSystemVideo;
import com.joysuch.wwyt.bp.enums.*;
import com.joysuch.wwyt.bp.mapper.BpStorageTankMapper;
import com.joysuch.wwyt.bp.mapper.AlarmMessageMapper;
import com.joysuch.wwyt.bp.mapper.InspectExceptionAlarmMesageMapper;
import com.joysuch.wwyt.bp.repository.*;
import com.joysuch.wwyt.bp.service.*;
import com.joysuch.wwyt.config.RedisClient;
import com.joysuch.wwyt.core.bean.SimpleSelectListBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.*;
import com.joysuch.wwyt.core.common.util.MapUtils.ThreeDPoints;
import com.joysuch.wwyt.core.common.util.PageDataUtils.PageDataConvert;
import com.joysuch.wwyt.core.constant.Constants;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.entity.BaseUser;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.enums.DeleteFlag;
import com.joysuch.wwyt.core.enums.RiskLevels;
import com.joysuch.wwyt.core.enums.Status;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.mh.BizUtils;
import com.joysuch.wwyt.mh.bean.MonitorWebSocketPointAlarmData;
import com.joysuch.wwyt.mh.entity.*;
import com.joysuch.wwyt.mh.entity.dsl.QMhMajorHazard;
import com.joysuch.wwyt.mh.entity.dsl.QMhMonitoringPoint;
import com.joysuch.wwyt.mh.enums.MajorHazardLevelEnum;
import com.joysuch.wwyt.mh.enums.MonitorTypeEnum;
import com.joysuch.wwyt.mh.mapper.MhAlarmRecordMapper;
import com.joysuch.wwyt.mh.repository.MhAlarmMessageDao;
import com.joysuch.wwyt.mh.repository.MhMajorHazardDao;
import com.joysuch.wwyt.mh.repository.MhMonitoringPointDao;
import com.joysuch.wwyt.mh.repository.MhMonitoringTypeDao;
import com.joysuch.wwyt.mh.service.*;
import com.joysuch.wwyt.mh.storage.IMonitorPointDataService;
import com.joysuch.wwyt.mh.storage.MonitorPointData;
import com.joysuch.wwyt.monitoringcenter.bean.*;
import com.joysuch.wwyt.monitoringcenter.bean.DistrictRiskDetailBean.ControlRiskLevelInfo;
import com.joysuch.wwyt.monitoringcenter.bean.DistrictRiskDetailBean.SheetDetailInfo;
import com.joysuch.wwyt.monitoringcenter.bean.MonitoringPointDetailBean.BaseInfo;
import com.joysuch.wwyt.monitoringcenter.bean.MonitoringPointDetailBean.HistoryValue;
import com.joysuch.wwyt.monitoringcenter.bean.MonitoringPointDetailBean.WarnInfo;
import com.joysuch.wwyt.monitoringcenter.service.AlarmCenterService;
import com.joysuch.wwyt.monitoringcenter.service.LocateServerService;
import com.joysuch.wwyt.monitoringcenter.service.MonitoringCenterService;
import com.joysuch.wwyt.risk.bean.RiskControlSearchBean;
import com.joysuch.wwyt.risk.bean.RiskEvaluationBusinessShowBean;
import com.joysuch.wwyt.risk.entity.*;
import com.joysuch.wwyt.risk.entity.dsl.QRiskEvaluationAlarmMesage;
import com.joysuch.wwyt.risk.repository.*;
import com.joysuch.wwyt.risk.service.RiskDistrictService;
import com.joysuch.wwyt.risk.service.RiskDynamicRecordService;
import com.joysuch.wwyt.risk.service.RiskEvaluationBusinessService;
import com.joysuch.wwyt.util.PageableUtil;
import com.joysuch.wwyt.workflow.bean.*;
import com.joysuch.wwyt.workflow.entity.WorkFlowProcess;
import com.joysuch.wwyt.workflow.entity.WorkFlowScreenConfig;
import com.joysuch.wwyt.workflow.entity.WorkFlowScreenType;
import com.joysuch.wwyt.workflow.repository.WorkFlowProcessDao;
import com.joysuch.wwyt.workflow.repository.WorkFlowScreenConfigDao;
import com.joysuch.wwyt.workflow.repository.WorkFlowScreenTypeDao;
import com.joysuch.wwyt.workflow.service.WorkFlowProcessService;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.geo.Point;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.joysuch.wwyt.bp.constant.ProcAlarmDefaultParam.DEFAULT_WF_INSPECT_ALARM_URL;
import static com.joysuch.wwyt.bp.constant.ProcAlarmDefaultParam.DEFAULT_WF_IP_ADDR;
import static com.joysuch.wwyt.common.constant.Constant.ATTRIBUTE_CODE;
import static com.joysuch.wwyt.common.constant.Constant.COMMON_SWITCH_ON;

@Service
@Transactional
@Slf4j
public class MonitoringCenterServiceImpl implements MonitoringCenterService {

    @Value("${wwyt.base.serverUrl}")
    private String serverUrl;

    @Autowired
    private RiskDistrictService districtService;
    @Autowired
    private RiskDistrictDao districtDao;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private RiskPromiseCardDao promiseCardDao;
    @Autowired
    private RiskShouldKnowCardDao shouldKnowCardDao;
    @Autowired
    private RiskEmergencyCardDao emergencyCardDao;
    @Autowired
    private RiskPointDao riskPointDao;
    @Autowired
    private MhMonitoringPointDao monitoringPointDao;
    @Autowired
    private IMonitorPointDataService monitoringPointDataService;
    @Autowired
    private MhMajorHazardDao majorHazardDao;
    @Autowired
    private BpDeviceFacilityCollectionDao bpDeviceFacilityCollectionDao;
    @Autowired
    private BpWorkSafetyCertDao bpWorkSafetyCertDao;
    @Autowired
    private MhAlarmMessageDao mhAlarmMessageDao;
    @Autowired
    private RiskEvaluationAlarmMesageDao riskEvaluationAlarmMesageDao;
    @Autowired
    private LocateServerService localteServerService;
    @Resource
    private BaseConfigService baseConfigService;
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private BpProductionFacilityDao facilityDao;
    @Autowired
    private BpDeviceFacilityMonitoringPointDao bpDeviceFacilityMonitoringPointDao;
    @Autowired
    private BpDeviceFacilityCollectionService facilityService;
    @Autowired
    private MhMonitoringPointService mhMonitoringPointService;
    @Autowired
    private BpSystemVideoDao bpSystemVideoDao;
    @Autowired
    private BpStorageTankDao storageTankDao;
    @Autowired
    private BpStorageTankAreaDao storageTankAreaDao;
    @Autowired
    private BpStoreHouseDao storeHouseDao;
    @Autowired
    private BpStoreAreaDao storeAreaDao;
    @Autowired
    private MhMonitoringTypeDao mhMonitoringTypeDao;
    @Autowired
    private IMonitorPointDataService monitorPointDataService;
    @Autowired
    private LocateServerService locateServerService;
    @Autowired
    private WorkFlowProcessService workFlowProcessService;
    @Autowired
    private RiskEvaluationBusinessService riskEvaluationBusinessService;
    @Autowired
    private RiskPointTypeDao riskPointTypeDao;
    @Autowired
    private OrientationDataSyncService orientationDataSyncService;
    @Autowired
    private BpStoreHouseService bpStoreHouseService;
    @Autowired
    private BpStoreHouseDao bpStoreHouseDao;
    @Autowired
    private MonitorPointDataWebSocketService monitorPointDataWebSocketService;
    @Autowired
    private WorkFlowScreenTypeDao workFlowScreenTypeDao;
    @Autowired
    private WorkFlowScreenConfigDao workFlowScreenConfigDao;
    @Autowired
    private WorkFlowProcessDao workFlowProcessDao;
    @Autowired
    private BpProductionFacilityDao bpProductionFacilityDao;
    @Autowired
    private CustomizeMonitorPointService customizeMonitorPointService;
    @Autowired
    private BpManufacturingTechDao bpManufacturingTechDao;
    @Autowired
    private BpMonitoringPointRelDao bpMonitoringPointRelDao;
    @Autowired
    private BpEmergencyContingencyPlanService planService;
    @Autowired
    private MhMonitoringRealTimeService mhMonitoringRealTimeService;
    @Autowired
    private BpContractorStaffDao BpContractorStaffDao;
    @Autowired
    private MonitorPointDataWebSocketService webSocketService;
    @Autowired
    private InspectExceptionAlarmMesageService inspectExceptionAlarmMesageService;
    @Autowired
    private AlarmCenterService alarmCenterService;
    @Autowired
    private CustomAlarmMessageService customAlarmMessageService;
    @Autowired
    private AlarmMessageService alarmMessageService;
    @Autowired
    private RiskEvaluationControlDao controlDao;
    @Autowired
    private RiskDynamicRecordService riskDynamicRecordService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private InspectExceptionAlarmMesageMapper inspectExceptionAlarmMesageMapper;
    @Autowired
    private AlarmMessageMapper alarmMessageMapper;

    @Autowired
    private BpProductionFacilityVideoDao productionFacilityVideoDao;

    @Resource
    private MhAlarmRecordMapper alarmMapper;

    @Resource
    private BpStorageTankMapper storeMapper;


    private static final ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(10, r -> {
        Thread thread = new Thread(r, "alarmMessage worker");
        thread.setDaemon(true);
        return thread;
    });

//    private static final ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();

    @Override
    public DistrictRiskDetailBean queryDistrictRiskDetail(Pageable pageable, Long districtId, String version) {
        RiskDistrict district = districtService.findById(districtId);
        if (district == null) {
            return null;
        }
        DistrictRiskDetailBean bean = new DistrictRiskDetailBean();

        DistrictRiskDetailBean.DistrictInfo baseInfo = new DistrictRiskDetailBean.DistrictInfo();
        baseInfo.setName(district.getName());
        baseInfo.setNumber(district.getCode());
        if (district.getRiskDistrictEvaluation() != null) {
            if (district.getRiskDistrictEvaluation().getEvaluationUserId() != null) {
                BaseUser evaluateUser = baseUserDao.findById(district.getRiskDistrictEvaluation().getEvaluationUserId()).get();
                if (evaluateUser != null) {
                    baseInfo.setPeople_assess(evaluateUser.getRealName());
                }
            }
//            baseInfo.setAreaDangerLevel(
//                    RiskLevels.findRiskLevelName(district.getRiskDistrictEvaluation().getRiskLevel()));
            baseInfo.setAreaDangerLevel(
                    RiskLevels.findRiskLevelName(district.getRiskLevel()));
            if (district.getRiskDistrictEvaluation().getEvaluationTime() != null) {
                baseInfo.setTime_assess(
                        SimpleDateFormatCache.getYmd().format(district.getRiskDistrictEvaluation().getEvaluationTime()));
            }
            if (district.getRiskDistrictEvaluation().getResponsiblePersonId() != null) {
                BaseUser responsibleUser = baseUserDao
                        .findById(district.getRiskDistrictEvaluation().getResponsiblePersonId()).get();
                baseInfo.setPerople_res(responsibleUser.getRealName());
            }
            //baseInfo.setCompany(district.getRiskDistrictEvaluation().getEvaluationOffice());
            RiskDistrictEvaluation evaluation = district.getRiskDistrictEvaluation();
            if (evaluation != null) {
                Long departId = evaluation.getResponsibleDepartId();
                //责任单位
                baseInfo.setResponsibleDepartName(departId == null ? "" : bpDepartDao.findDepartNameById(departId));
                //评估单位
                String office = evaluation.getEvaluationOffice();
                //兼容excel数据导入时传的是部门名称
                if (StringUtils.isNotBlank(office)) {
                    boolean number = isNumber(office);
                    if (number) {
                        baseInfo.setCompany(bpDepartDao.findDepartNameById(Long.parseLong(office)));
                    } else {
                        baseInfo.setCompany(office);
                    }
                } else {
                    baseInfo.setCompany("");
                }
                //固有风险等级
                baseInfo.setDangerLevel(RiskLevels.findRiskLevelName(evaluation.getStableRiskLevel()));

            }
        }
        //baseInfo.setDangerLevel(RiskLevels.findRiskLevelName(district.getRiskLevel()));
        bean.setBasicList(baseInfo);

        // 填充两单三卡信息
        List<RiskPoint> points = riskPointDao.findAllAuditedPointsByDistrictId(districtId);
        DistrictRiskDetailBean.CardListInfo card = new DistrictRiskDetailBean.CardListInfo();

        List<RiskPointType> pointTypeList = riskPointTypeDao.findAll();
        Map<String, String> typeNameMap = pointTypeList.stream().collect(Collectors.toMap(RiskPointType::getCode, RiskPointType::getName));
        if (!CollectionUtils.isEmpty(points)) {
            for (RiskPoint p : points) {
                SheetDetailInfo sheetDetailInfo = convert(p, typeNameMap);
                card.getListOne().add(sheetDetailInfo);
                card.getListTwo().add(sheetDetailInfo);
            }
        }
        RiskPromiseCard promiseCard = promiseCardDao.findFirstByRiskDistrictId(districtId);
        card.setCardOne(promiseCard == null ? "" : promiseCard.getContent());
        RiskEmergencyCard emergencyCard = emergencyCardDao.findFirstByRiskDistrictId(districtId);
        card.setCardTwo(emergencyCard == null ? "" : emergencyCard.getContent());
        RiskShouldKnowCard shouldKnowCard = shouldKnowCardDao.findFirstByRiskDistrictId(districtId);
        card.setCardThree(shouldKnowCard == null ? "" : shouldKnowCard.getContent());
        bean.setCardList(card);
        RiskEvaluationControl control = controlDao.findByName("风险四色图计算逻辑");
        // 填写风险管控信息
        if (version != null && version.equals("2.0")) {
            RiskEvaluationBusinessShowBean business = riskEvaluationBusinessService.getBusinessById(districtId);
            if (control != null && control.getSwitchState() == 0) {
                business.setRiskLevel(district.getStableRiskLevel());
                business.setRiskLevelName(RiskLevels.findRiskLevelName(district.getStableRiskLevel()));
            } else {
                //展示实时等级
                business.setRiskLevel(RiskLevels.getRealLevelIntValue(district.getRealTimeRiskLevel()));
                business.setRiskLevelName(RiskLevels.getRealLevelIntValueName(district.getRealTimeRiskLevel()));
            }
            bean.setDistrictShowBean(business);
            RiskControlSearchBean searchBean = new RiskControlSearchBean();
            searchBean.setDistrictId(districtId);
        }
        return bean;
    }


    //判断风是否是数字类型
    private boolean isNumber(String str) {
        for (int i = 0; i < str.length(); i++) {
            if (!Character.isDigit(str.charAt(i))) {//用java自带的函数
                return false;
            }
        }
        return true;
    }

    private ControlRiskLevelInfo convertToControlRiskLevelInfo(RiskPoint p, Map<String, String> typeNameMap) {
        ControlRiskLevelInfo info = new ControlRiskLevelInfo();
        info.setRiskPointId(p.getId());
        info.setLevel(RiskLevels.findRiskLevelName(p.getRiskLevel()));
        info.setName(p.getName());
        String typeName = typeNameMap.get(p.getType());
        if (StringUtils.isNotBlank(typeName)) {
            info.setType(typeName);
        } else {
            info.setType(RiskPointTypes.findNameByCode(p.getType()));
        }
        /*if (p.getLastEvaluationTime() != null) {
            info.setTime(SimpleDateFormatCache.getYmd().format(p.getLastEvaluationTime()));
            RiskPointEvaluationJha jha = riskEvaluationRepoService.findMostImportantJhaOfRiskPoint(p.getId());
            // 如果评估时间为null，则没有评估数据
            if (jha != null && jha.getBaseUser() != null) {
                info.setPeople(jha.getBaseUser().getRealName());
            } else {
                RiskPointEvaluationScl scl = riskEvaluationRepoService.findMostImportantSclOfRiskPoint(p.getId());
                if (scl != null && scl.getBaseUser() != null) {
                    info.setPeople(scl.getBaseUser().getRealName());
                }
            }
        }*/
        return info;
    }

    private String trueOrFalseToString(boolean b) {
        return b ? "Y" : "N";
    }

    private SheetDetailInfo convert(RiskPoint p, Map<String, String> typeNameMap) {
        SheetDetailInfo info = new SheetDetailInfo();
        info.setArea(p.getName());
        if (p.getResponsibleDepart() != null) {
            info.setCompany(p.getResponsibleDepart().getName());
        }
        if (p.getResponsibleUser() != null) {
            info.setPeople(p.getResponsibleUser().getRealName());
        }
        String typeName = typeNameMap.get(p.getType());
        if (StringUtils.isNotBlank(typeName)) {
            info.setType(typeName);
        } else {
            info.setType(RiskPointTypes.findNameByCode(p.getType()));
        }
        if (p.getControlLevelId() != null) {
            info.setLevel(RiskLevels.findRiskNameByCode(p.getRiskLevel()));
        }
        info.setSource("");
        // info.setRiskIdentifyContent(RiskPointUtil.extractRiskIdentifyContentForWeb(p));
        //存在的主要危险(有害)因素
        info.setUnstandardSituationConsequence(p.getUnstandardSituationConsequence());
        // 容易发生的事故类型
        info.setAccidentType(p.getAccidentType());
        return info;
    }

    @Override
    public DistrictInfoReturnBean queryRiskDistrictList() {
        DistrictInfoReturnBean bean = new DistrictInfoReturnBean();
        List<RiskDistrict> all = districtDao.findAll();
        List<DistrictInfoBean> list = new ArrayList<>(all.size());
        for (RiskDistrict d : all) {
            list.add(convertToDistrictInfoBean(d));
        }
        RiskEvaluationControl control = controlDao.findByName("风险四色图计算逻辑");
        if (control != null && control.getSwitchState() == 0) {
            list.forEach((e) -> {
                e.setLevel(e.getOwnLevel());
            });
        }
        list = list.stream()
                .sorted(Comparator.comparing(DistrictInfoBean::getLevel, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        bean.setBeanList(list);
        List<RiskPoint> points = riskPointDao.findAllByShared(3);
        if (!CollectionUtils.isEmpty(points)) {
            bean.setTotalPointCount(points.size());
        } else {
            bean.setTotalPointCount(0);
        }
        return bean;
    }

    private DistrictInfoBean convertToDistrictInfoBean(RiskDistrict d) {
        DistrictInfoBean b = new DistrictInfoBean();
        b.setId(d.getId());
        b.setName(d.getName());
        //b.setLevel(d.getRiskLevel());
        //2.7取实时值
        b.setLevel(RiskLevels.getRealLevelIntValue(d.getRealTimeRiskLevel()));
        b.setOwnLevel(d.getStableRiskLevel());
        //查询风险区域报警未处理数量
        int number = riskEvaluationAlarmMesageDao.countDistrictNumber(d.getId(), 0);
        if (number > 0) {
            //异常
            b.setStatus(1);
        } else {
            //正常
            b.setStatus(0);
        }
        b.setPoints(MapUtils.parsePointsFromJson(d.getCoordinates()));
        b.setDangerCount(riskPointDao.pointCountInRiskDistrict(d.getId()).intValue());
        b.setLocation(d.getCoordinates());
        return b;
    }

    @Override
    public MonitoringPointDetailBean queryMonitoringPointDetail(Long monitoringPointId) throws ApiBusinessException {
        Optional<MhMonitoringPoint> optional = monitoringPointDao.findById(monitoringPointId);
        if (!optional.isPresent()) {
            throw new ApiBusinessException(Status.MONITOR_POINT_NOT_FIND_ERROR);
        }
        MhMonitoringPoint mp = optional.get();
        MonitoringPointDetailBean bean = new MonitoringPointDetailBean();
        // 基础信息
        BaseInfo baseInfo = new BaseInfo();
        baseInfo.setName(mp.getName());
        baseInfo.setNumber(mp.getPointCode());
        if (mp.getMhMonitoringType() != null) {
            baseInfo.setType(mp.getMhMonitoringType().getName());
            baseInfo.setUnit(mp.getMhMonitoringType().getUnit());
        }
        baseInfo.setFirstValue(mp.getLevel1Threshold());
        baseInfo.setSecondValue(mp.getLevel2Threshold());
        baseInfo.setLowValue1(mp.getLowValue1());
        baseInfo.setLowValue2(mp.getLowValue2());
        baseInfo.setHighValue1(mp.getHighValue1());
        baseInfo.setHighValue2(mp.getHighValue2());
        bean.setMonitorList(baseInfo);

        // 实时数值
        Optional<MonitorPointData> val = monitoringPointDataService.realTimeVal(Context.getCurrentTenantId(),
                Context.getCompanyCode(), mp.getPointCode());
        if (val != null && val.isPresent()) {
            String value = val.get().getValue().toString();
            if (val.get().getExValue() != null) {
                value = val.get().getExValue();
            }
            bean.setCurrentValue(value, baseInfo.getUnit());
        }

        // 历史数值
        Calendar now = Calendar.getInstance();
        Date endTime = now.getTime();
        now.add(Calendar.HOUR, -6);
        Date startTime = now.getTime();
        String startTimeStr = SimpleDateFormatCache.getYmdhms().format(startTime);
        String endTimeStr = SimpleDateFormatCache.getYmdhms().format(endTime);

        // todo flag ?
        List<MonitorPointData> historyVals = monitoringPointDataService.historyVals(Context.getCurrentTenantId(),
                Context.getCompanyCode(), mp.getPointCode(), startTimeStr, endTimeStr, 0);
        bean.setMonitorValueList(convertMonitoringValueList(historyVals, baseInfo));

        // 报警信息列表
        // FIXME 查询多长时间范围内的报警记录？
        //List<MhAlarmMessage> messages = mhAlarmMessageDao.selectLastAlarmMessagesOfMinitoringPoint(monitoringPointId, 10);
        List<MhAlarmMessage> messages = mhAlarmMessageDao.selectAlarmMessagesOfMinitoringPoint(monitoringPointId);
        bean.setWarnList(convertToWarnInfoList(messages));
        return bean;
    }

    //监测点报警记录
    private List<WarnInfo> convertToWarnInfoList(List<MhAlarmMessage> messages) {
        List<WarnInfo> list = new ArrayList<>();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        //级别
        for (MhAlarmMessage m : messages) {
            WarnInfo w = new WarnInfo();
            if (m.getLevel() != null) {
                w.setLevel(m.getLevel() == 1 ? "一级" : "二级");
            }
            //处理状态
            if (m.getState() != null && m.getState() == 2) {
                w.setSolveStatus("已解决");
            } else {
                w.setSolveStatus("未解决");
            }
            if (m.getHandleTime() != null) {
                w.setSolveTime(m.getHandleTime().format(df));
            }
            //报警值
            w.setValue(m.getValue());
            //报警时间
            w.setTime(m.getAlarmTime().format(df));
            list.add(w);
        }
        return list;
    }


    @Override
    public List<WarnInfo> getAlarmByPoint(Long id, Date startTime, Date endTime) {
        List<MhAlarmMessage> messages = mhAlarmMessageDao.selectAlarmMessagesOfMinitoringPointAndTime(id, startTime, endTime);
        if (CollectionUtils.isEmpty(messages)) {
            return new ArrayList<>();
        }
        return convertToWarnInfoList(messages);
    }

    private List<HistoryValue> convertMonitoringValueList(List<MonitorPointData> historyVals, BaseInfo baseInfo) {
        List<HistoryValue> list = new ArrayList<>(historyVals.size());
        for (MonitorPointData d : historyVals) {
            HistoryValue h = new HistoryValue();

            h.setTime(SimpleDateFormatCache.getYmdhms().format(new Date(d.getTime() * 1000)));
            h.setUnit(baseInfo.getUnit());
            h.setValue(d.getValue());
            list.add(h);
        }
        return list;
    }

    /**
     * 大屏-重大危险源监测详情
     *
     * @param id 重大危险源ID
     * @return
     */
    @Override
    public MonitoringDetailsMajorHazardSourcesBean queryMajorHazardDetail(Long id) {
        MonitoringDetailsMajorHazardSourcesBean re = new MonitoringDetailsMajorHazardSourcesBean();
        Optional<MhMajorHazard> omh = majorHazardDao.findById(id);
        if (omh.isPresent()) {
            MhMajorHazard mh = omh.get();
            // 基础信息
            MajorHazardBean mhb = new MajorHazardBean();
            mhb.setId(mh.getId());
            mhb.setName(mh.getName());
            mhb.setLevel(mh.getLevel());
            mhb.setRValue(mh.getRvalue());
            if (mh.getRiskDistrictId() != null) {
                mhb.setArea(districtDao.getOne(mh.getRiskDistrictId()).getName());
            }
            re.setDangerSourceList(mhb);
            List<ChemProductBean> clist = parseMajorHazardChemicalInfo(mh);
            re.setDangerArticleList(clist);
            re.setMonitorList(queryMhMonitorList(mh));
            re.setCameraList(mockMonitorProbeInformation());
            //根据重大危险源id查询关联设备设施id集合
            List<Long> facilityIds = bpProductionFacilityDao.findByMajorHazardId(id);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(facilityIds)) {
                List<Long> facilityVideoIds = productionFacilityVideoDao.findByFacilityIds(facilityIds);
                if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(facilityVideoIds)) {
                    List<BpSystemVideo> videoList = bpSystemVideoDao.findByIds(facilityVideoIds);
                    if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(videoList)) {
                        List<BpSystemVideoAddBean> beans = new ArrayList<>();
                        for (BpSystemVideo bpSystemVideo : videoList) {
                            BpSystemVideoAddBean b = new BpSystemVideoAddBean();
                            BeanUtils.copyProperties(bpSystemVideo, b);
                            b.setDateFormat("yyyy-MM-dd");
                            b.setTimeFormat("mm:HH:dd");
                            if (StringUtils.isNotBlank(bpSystemVideo.getEvaluation())) {
                                Optional<RiskDistrict> districtOperation = districtDao.findById(new Long(bpSystemVideo.getEvaluation()));
                                districtOperation.ifPresent(riskDistrict -> b.setEvaluationName(riskDistrict.getName()));
                                b.setEvaluationId(bpSystemVideo.getEvaluation());
                            }
                            beans.add(b);
                        }
                        re.setVideoList(beans);
                    }
                }
            }
        }
        return re;
    }


    // 重大危险源-设备设施-监控点
    private List<MonitoringPointBean> queryMhMonitorList(MhMajorHazard mh) {
        List<BpDeviceFacilityCollection> devices = bpDeviceFacilityCollectionDao.findByMajorHazardId(mh.getId());
        if (devices.size() > 0) {
            List<MonitoringPointBean> list = new ArrayList<>();
            Set<Long> ids = Sets.newHashSet();
            for (BpDeviceFacilityCollection c : devices) {
                for (MhMonitoringPoint p : c.getMhMonitoringPoints()) {
                    if (ids.contains(p.getId())) {
                        continue;
                    }
                    ids.add(p.getId());
                    MonitoringPointBean bean = new MonitoringPointBean();
                    bean.setId(p.getId());
                    bean.setLocaltion(c.getDistrictName());
                    //需求变更-显示监测点名称
                    bean.setName(p.getName());
                    if (p.getMhMonitoringType() != null) {
                        bean.setType(p.getMhMonitoringType().getName());
                    }
                    //状态 0正常,1,异常,2未连接
                    MhValueAndStateBean valueAndStateBean = getSwitchState(p);
                    if (valueAndStateBean.getState() != null && valueAndStateBean.getState() == 0) {
                        Double val = mhMonitoringPointService.realTimeVal(p);
                        bean.setValue(this.getPointValueByTypeUnits(p, val));
                    } else if (valueAndStateBean.getState() != null && valueAndStateBean.getState() == 2) {
                        bean.setValue("未连接");
                    }
                    Integer flag = getAlarmFlag(p);
                    if (flag == 1) {
                        valueAndStateBean.setState(1);
                    }
                    bean.setRealtimeValue(valueAndStateBean.getRealTimeValue());
                    bean.setStatus(valueAndStateBean.getState());
                    list.add(bean);
                }
            }
            return list;
        }
        return Collections.EMPTY_LIST;
    }

    // 监控探头信息
    private List<MonitorProbeInformationBean> mockMonitorProbeInformation() {
        MonitorProbeInformationBean monitorProbeInformationBean = new MonitorProbeInformationBean();
        monitorProbeInformationBean.setArea("area");
        monitorProbeInformationBean.setName("test");
        monitorProbeInformationBean.setRtmp("rtmp://58.221.237.218/pusher/192.168.1.1_8080_chemical");
        monitorProbeInformationBean.setStatus(0);
        List<MonitorProbeInformationBean> list = new ArrayList<>();
        list.add(monitorProbeInformationBean);
        return list;
    }

    private List<ChemProductBean> parseMajorHazardChemicalInfo(MhMajorHazard mh) {
        if (mh.getMhMajorHazardChemProductRels().size() == 0) {
            return Collections.EMPTY_LIST;
        }
        List<ChemProductBean> list = new ArrayList<>(mh.getMhMajorHazardChemProductRels().size());
        for (MhMajorHazardChemProductRel r : mh.getMhMajorHazardChemProductRels()) {
            MhMajorHazardChemProduct chem = r.getMhMajorHazardChemProduct();
            if (chem != null) {
                ChemProductBean bean = new ChemProductBean();
                bean.setId(chem.getId());
                bean.setCsc(chem.getCasNo());
                bean.setMostCount(r.getCriticalStock());
                bean.setUseCount(r.getStock());
                bean.setQuality(r.getChemProductFeature());
                bean.setName(chem.getName());
                bean.setUse(r.getUsage());
                bean.setType(chem.getType());
                list.add(bean);
            }
        }
        return list;
    }

    @Override
    public List<BpWorkSafetyCertSimpleBean> queryAllInProgressingWorkSafetyCerts() {
        List<BpWorkSafetyCert> jobs = bpWorkSafetyCertDao.findInProgressingJob();
        return PageDataUtils.convertListData(jobs, new PageDataConvert<BpWorkSafetyCertSimpleBean, BpWorkSafetyCert>() {

            @Override
            public BpWorkSafetyCertSimpleBean convert(BpWorkSafetyCert f) {
                BpWorkSafetyCertSimpleBean bean = new BpWorkSafetyCertSimpleBean();
                bean.setId(f.getId());
                bean.setType(f.getType());
                bean.setStatus(SafetyWorkStates.findNameById(f.getState()));
                ThreeDPoints points = MapUtils.parse3DPointsFromJson(f.getLocationCoords());
                if (points != null) {
                    bean.setFloorId(points.getFloorId());
                    Point centerPoint = MapUtils.calculateCenterPoint(points.getPoints());
                    bean.setX(centerPoint.getX());
                    bean.setY(centerPoint.getY());
                }
                return bean;
            }
        });
    }

    /**
     * 计算坐标点偏移量
     *
     * @param coordinate 坐标
     * @param min        随机数最小值
     * @param max        随机数最大值
     * @param f          系数
     * @return
     */
    public double offsetCoordinate(Double coordinate, Integer min, Integer max, Double f) {
        if (coordinate != null && min != null && max != null) {
            if (min > max) {
                int a = max;
                max = min;
                min = a;
            }
            double v = min + Math.random() * (max - min + 1);
            if (v > (max - min) / 2) {
                return coordinate + v * f;
            } else {
                return coordinate - v * f;
            }

        } else {
            return 0;
        }
    }

    @Override
    public List<McAlarmMessageBean> queryAlarmMessages(String type, Long riskDistrictId, Integer state, int offset,
                                                       int count) {
        if (type == null) {
            List<McAlarmMessageBean> mhList = queryMajorHazardAlarmMessage(state);
            List<McAlarmMessageBean> riskList = queryRiskAlarmMessage(riskDistrictId, state);
            //List<McAlarmMessageBean> locateList = localteServerService.alarmMessages();

            //mhList.addAll(locateList);
            mhList.addAll(riskList);

            Collections.sort(mhList, new Comparator<McAlarmMessageBean>() {

                @Override
                public int compare(McAlarmMessageBean o1, McAlarmMessageBean o2) {
                    if (o1.getTime() != null && o2.getTime() != null) {
                        return o2.getTime().compareTo(o1.getTime());
                    } else if (o1.getTime() != null) {
                        return -1;
                    } else if (o2.getTime() != null) {
                        return 1;
                    }
                    return 0;
                }
            });
            return mhList.size() > 100 ? mhList.subList(0, 100) : mhList;
        } else {
            switch (type) {
                case "重大危险源":
                    List<McAlarmMessageBean> mbList = queryMajorHazardAlarmMessage(state);
                    return mbList;
                case "风险分区":
                    return queryRiskAlarmMessage(riskDistrictId, state);
                case "巡检排查":
                    return inspectExceptionAlarmMesageService.queryInspectException(state, Context.getCurrentTenantId(), Context.getCurrentOrgCode());
                case "AI报警":
                    return alarmMessageService.queryAIAlarmMessage(state, ApiAlarmTypeEnum.getIdByName(type));
                case "人员在岗在位报警":
                    return alarmMessageService.queryAIAlarmMessage(state, ApiAlarmTypeEnum.getIdByName(type));
                case "作业票报警":
                    return alarmMessageService.queryAIAlarmMessage(state, ApiAlarmTypeEnum.getIdByName(type));
                case "车辆报警":
                    return alarmMessageService.queryAIAlarmMessage(state, ApiAlarmTypeEnum.getIdByName(type));
                default:
                    return localteServerService.alarmMessages();
            }
        }

    }

    private String builderRedisConfigKey() {
        Long tenantId = Context.getCurrentTenantId();
        String orgCode = Context.getCurrentOrgCode();
        return String.format(Constants.ALARM_CENTER_COUNT_REDIS_KEY, tenantId, orgCode);
    }

    @Override
    public ResultBean alarmMessageCount(String buildId) {
          String totalCount = redisClient.get(builderRedisConfigKey());
          if(totalCount != null){
              return ResultBean.success(totalCount);
          }else{
              // 监测点报警
              int count = mhAlarmMessageDao.checkCount(Context.getCurrentTenantId(), Context.getCurrentOrgCode());
              if(count >0){
                  redisClient.setEx(builderRedisConfigKey(), String.valueOf(count), 10, TimeUnit.SECONDS);
                  return ResultBean.success(count);
              }
              //隐患排查报警数量
              count = riskEvaluationAlarmMesageDao.checkCount(Context.getCurrentTenantId(), Context.getCurrentOrgCode());
              if(count >0){
                  redisClient.setEx(builderRedisConfigKey(), String.valueOf(count), 10, TimeUnit.SECONDS);
                  return ResultBean.success(count);
              }
              //隐患排查报警数量
               count = inspectExceptionAlarmMesageMapper.checkCount(Context.getCurrentTenantId(), Context.getCurrentOrgCode());
              if(count >0){
                  redisClient.setEx(builderRedisConfigKey(), String.valueOf(count), 10, TimeUnit.SECONDS);
                  return ResultBean.success(count);
              }
              //AI报警数量
              List<Integer> typeList = new ArrayList<>();
              typeList.add(ApiAlarmTypeEnum.AI.getId());
              typeList.add(ApiAlarmTypeEnum.AREA_ALARM.getId());
              typeList.add(ApiAlarmTypeEnum.JOBA_LARM_EVENT.getId());
              typeList.add(ApiAlarmTypeEnum.ALARM_EVENT.getId());
              count = alarmMessageMapper.checkCount(Context.getCurrentTenantId(), Context.getCurrentOrgCode());
              if(count >0){
                  redisClient.setEx(builderRedisConfigKey(), String.valueOf(count), 10, TimeUnit.SECONDS);
                  return ResultBean.success(count);
              }
              try {
                  BaseConfig config = baseConfigService.findConfig(Context.getCurrentTenantId(), Context.getCompanyCode(), "locate.version");
                  if (config != null && config.getValue().equals("4.x")) {
                      redisClient.setEx(builderRedisConfigKey(), String.valueOf(count), 10, TimeUnit.SECONDS);
                      return ResultBean.success(count);
                  } else {
                      // 3.X
                      if (buildId == null) {
                          redisClient.setEx(builderRedisConfigKey(), String.valueOf(count), 10, TimeUnit.SECONDS);
                          return ResultBean.success(count);
                      }
                    count = locateServerService.getLocateAlarmCount(buildId);
                    redisClient.setEx(builderRedisConfigKey(), String.valueOf(count), 10, TimeUnit.SECONDS);
                    return ResultBean.success(count);
                  }
              } catch (Exception e) {
                  log.error(e.getMessage(), e);
                  return ResultBean.success(0);
              }
          }

    }

    /**
     * @param state
     * @return
     */
    protected List<McAlarmMessageBean> queryMajorHazardAlarmMessage(Integer state) {
        if (state != null) {
            //state:0  未处理=报警中+回到正常值
            if (state == 0) {
                List<MhAlarmMessage> list = mhAlarmMessageDao.findTop100ByStateOrderByCreateTimeDesc();
                return convert(list);
            } else {
                List<MhAlarmMessage> list = mhAlarmMessageDao.findTop100ByStateOrderByCreateTimeDesc(state);
                return convert(list);
            }
        } else {
            List<MhAlarmMessage> list = mhAlarmMessageDao.findTop100OrderByCreateTimeDesc();
            return convert(list);
        }
    }

    /**
     * @param riskDistrictId
     * @param state
     * @return
     */
    protected List<McAlarmMessageBean> queryRiskAlarmMessage(Long riskDistrictId, Integer state) {
        Page<RiskEvaluationAlarmMesage> messages = getRiskEvaluationAlarmMesages(riskDistrictId, state);
        return convert(messages);
    }

    @Override
    public Page<RiskEvaluationAlarmMesage> getRiskEvaluationAlarmMesages(Long riskDistrictId, Integer state) {
        QRiskEvaluationAlarmMesage qm = QRiskEvaluationAlarmMesage.riskEvaluationAlarmMesage;
        Predicate p = qm.isNotNull();
        if (riskDistrictId != null) {
            p = qm.riskDistrictId.eq(riskDistrictId);
        }
        if (state != null) {
            p = ExpressionUtils.and(p, qm.state.eq(state));
        }
        return riskEvaluationAlarmMesageDao.findAll(p, PageRequest.of(0, 100, Sort.by(Sort.Order.desc("createTime"))));
    }

    private List<McAlarmMessageBean> convert(Page<RiskEvaluationAlarmMesage> messages) {
        Map<Long, String> map = getDirtricCoordiantesMap();
        List<McAlarmMessageBean> list = new ArrayList<>(messages.getSize());
        for (RiskEvaluationAlarmMesage message : messages) {
            McAlarmMessageBean bean = new McAlarmMessageBean();
            bean.setId(message.getId());
            bean.setModule("风险分区");
            bean.setType("风险分级");
            bean.setAlarmLevel("二级报警");
            bean.setState(message.getState());
            bean.setRiskDistrictId(message.getRiskDistrictId());
            if (message.getRiskDistrictId() != null) {
                RiskDistrict district = districtDao.getOne(message.getRiskDistrictId());
                if (district != null) {
                    bean.setTitle("风险区域级别升高");
                    bean.setContent(extractRiskLevelAlarmMessage(message, district));
                    if (StringUtils.isNotBlank(map.get(message.getRiskDistrictId()))) {
                        ThreeDPoints points = MapUtils.parse3DPointsFromJson(district.getCoordinates());
                        if (points != null) {
                            bean.setFloorId(points.getFloorId());
                            Point centerPoint = MapUtils.calculateCenterPoint(points.getPoints());
                            bean.setX(centerPoint.getX());
                            bean.setY(centerPoint.getY());
                        }
                    }
                }
            }
            try {
                bean.setTime(SimpleDateFormatCache.getYmdhms().format(message.getCreateTime()));
            } catch (Exception e) {
            }
            list.add(bean);
        }
        return list;
    }

    private Map<Long, String> getDirtricCoordiantesMap() {
        Map<Long, String> map = new HashMap<>();
        List<RiskDistrict> all = districtDao.findAll();
        for (RiskDistrict district : all) {
            map.put(district.getId(), district.getCoordinates());
        }
        return map;
    }

    private List<McAlarmMessageBean> convert(List<MhAlarmMessage> messages) {
        List<McAlarmMessageBean> list = new ArrayList<>(messages.size());
        for (MhAlarmMessage one : messages) {
            McAlarmMessageBean bean = new McAlarmMessageBean();
            bean.setId(one.getId());
            bean.setModule("重大危险源");
            bean.setState(one.getState());
            //报警等级
            if (one.getLevel() == 1 || one.getLevel() == 2) {
                bean.setAlarmLevel("一级报警");
            } else {
                bean.setAlarmLevel("二级报警");
            }
            try {
                LocalDateTime createTime = one.getCreateTime();
                bean.setTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(createTime));
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            if (one.getMhMonitoringPoint() != null) {
                MonitorWebSocketPointAlarmData data = webSocketService.covertPointAlarmData(one.getMhMonitoringPoint(), new MonitorWebSocketPointAlarmData(), one);
                bean.setClassify(data.getClassify());
                bean.setPointTypeCode(data.getPointTypeCode());
                bean.setType(data.getPointTypeName());
                bean.setDeviceId(data.getDeviceId());
                bean.setMhHazardId(data.getMhHazardId());
                bean.setPointId(one.getMhMonitoringPoint().getId());
                BpMonitoringPointRel monitoringPointRel = bpMonitoringPointRelDao.findFirstByMonitoringPointId(bean.getPointId());
                //设备id
                if (monitoringPointRel != null) {
                    List<Long> facilityVideoIds = productionFacilityVideoDao.findByFacilityId(monitoringPointRel.getRefId());
                    if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(facilityVideoIds)) {
                        List<BpSystemVideo> videoList = bpSystemVideoDao.findByIds(facilityVideoIds);
                        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(videoList)) {
                            List<BpSystemVideoAddBean> beans = new ArrayList<>();
                            for (BpSystemVideo bpSystemVideo : videoList) {
                                BpSystemVideoAddBean b = new BpSystemVideoAddBean();
                                BeanUtils.copyProperties(bpSystemVideo, b);
                                b.setDateFormat("yyyy-MM-dd");
                                b.setTimeFormat("mm:HH:dd");
                                if (StringUtils.isNotBlank(bpSystemVideo.getEvaluation())) {
                                    Optional<RiskDistrict> districtOperation = districtDao.findById(new Long(bpSystemVideo.getEvaluation()));
                                    districtOperation.ifPresent(riskDistrict -> b.setEvaluationName(riskDistrict.getName()));
                                    b.setEvaluationId(bpSystemVideo.getEvaluation());
                                }
                                beans.add(b);
                            }
                            bean.setVideoList(beans);
                        }
                    }
                }
            }
            bean.setTitle(bean.getType() + "报警");
            bean.setContent(extranctMhAlarmContent(one));
            list.add(bean);
        }
        return list;
    }

    private String extractRiskLevelAlarmMessage(RiskEvaluationAlarmMesage message, RiskDistrict district) {
        StringBuilder sb = new StringBuilder();
        sb.append("\"").append(district.getName()).append("\"").append(message.getDetail());
        return sb.toString();
    }

    @Override
    public String extranctMhAlarmContent(MhAlarmMessage one) {
        MhMonitoringPoint point = one.getMhMonitoringPoint();
//        List<BpDeviceFacilityCollection> collections = bpDeviceFacilityCollectionDao
//                .queryMonitoringPointBindDevice(point.getId());
//        if (collections.size() > 0) {
        StringBuilder sb = new StringBuilder();
        sb.append("\"").append(point.getName()).append("\"").append(one.getDetail());
        return sb.toString();
//        } else {
//            StringBuilder sb = new StringBuilder();
//            sb.append("\"").append(point.getName()).append("\"");
//            return sb.toString();
//        }
    }

    private Object translateLevel(Integer level) {
        return level == 1 ? "一级报警" : "二级报警";
    }

    ThreadLocal<Pattern> valuePattern = new ThreadLocal<>();

    private Object extractAlarmValueFromDetail(String detail) {
        Pattern pattern = getPattern();
        Matcher m = pattern.matcher(detail);
        if (m.find()) {
            String group = m.group(1);
            return Double.parseDouble(group);
        }
        return "";
    }

    Pattern getPattern() {
        Pattern pattern = valuePattern.get();
        if (pattern == null) {
            pattern = Pattern.compile("当前报警数值([0-9]+(\\.[0-9]+)?)");
        }
        return pattern;
    }

    //handleFlag: 0 处理; 1 忽略
    @Override
    public void processAlarmMessage(String type, Long id, String msg, String alarmReason, Long handleBy, Integer handleFlag) {
        log.info("单条报警信息处理人：handleBy:{}", handleBy);
        if (handleBy == null) {
            handleBy = Context.getCurrentUserId();
        }
        log.info("单条报警信息处理：type：{},id:{},msg:{},alarmReason:{},handleBy:{},handleFlag:{}", type, id, msg, alarmReason, handleBy, handleFlag);
        processAlarmMessageBatch(Lists.newArrayList(new AlarmProcessBean(type, id, msg, alarmReason, handleBy, handleFlag)));
    }

    @Override
    public void processAlarmMessageBatch(List<AlarmProcessBean> list) {
        if (list == null) {
            return;
        }
        List<MhAlarmMessage> mhList = new ArrayList<>();
        List<RiskEvaluationAlarmMesage> riskList = new ArrayList<>();
        List<InspectExceptionAlarmMesage> inspectList = new ArrayList<>();
        List<AlarmMessage> alarmMessageList = new ArrayList<>();
        List<AlarmMessage> areaMessageList = new ArrayList<>();
        List<AlarmMessage> jobMessageList = new ArrayList<>();
        List<AlarmMessage> carMessageList = new ArrayList<>();
        Long tenentId = Context.getCurrentTenantId();
        String orgCode = Context.getCompanyCode();
        for (AlarmProcessBean alarm : list) {
            Integer handleFlag = alarm.getHandleFlag();
            if ("重大危险源".equals(alarm.getModule())) {
                MhAlarmMessage one = mhAlarmMessageDao.findById(alarm.getId()).orElseThrow(() -> new IllegalArgumentException("该数据不存在"));
                if (one.getState() != null && one.getState() != 2) {
                    one.setState(2);
                    if (handleFlag == 0) {
                        one.setRemark(alarm.getMsg());
                    } else {
                        one.setRemark("已忽略");
                    }
                    one.setHandleBy(baseUserDao.getRealNameById(alarm.getHandleBy()));
                    one.setHandleTime(LocalDateTime.now());
                    one.setAlarmReason(alarm.getAlarmReason());
                    mhList.add(one);
                }
            } else if ("风险分区".equals(alarm.getModule())) {
                RiskEvaluationAlarmMesage one = riskEvaluationAlarmMesageDao.getOne(alarm.getId());
                if (one.getState() != null && one.getState() != 1) {
                    one.setState(1);
                    if (handleFlag == 0) {
                        one.setHandleRemark(alarm.getMsg());
                    } else {
                        one.setHandleRemark("已忽略");
                    }
                    one.setAlarmReason(alarm.getAlarmReason());
                    one.setHandleBy(alarm.getHandleBy());
                    riskList.add(one);
                }
            } else if ("巡检排查".equals(alarm.getModule())) {

                LambdaQueryWrapper<InspectExceptionAlarmMesage> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(InspectExceptionAlarmMesage::getDeleteFlag, DeleteFlag.EFFECTIVE.getCode())
                        .eq(InspectExceptionAlarmMesage::getId, alarm.getId())
                        .eq(InspectExceptionAlarmMesage::getTenentId, tenentId)
                        .likeRight(InspectExceptionAlarmMesage::getOrgCode, orgCode);
                InspectExceptionAlarmMesage message = inspectExceptionAlarmMesageService.getOne(wrapper);
                if (message.getState() != null && message.getState() != 1) {
                    message.setState(1);
                    if (handleFlag == 0) {
                        message.setRemark(alarm.getMsg());
                    } else {
                        message.setRemark("已忽略");
                    }
                    message.setAlarmReason(alarm.getAlarmReason());
                    message.setHandleBy(alarm.getHandleBy());
                    message.setHandleTime(DateTime.now());
                    inspectList.add(message);
                }
            } else if ("AI报警".equals(alarm.getModule())) {
                convertHandleAlarmData(alarm, alarmMessageList);
            } else if ("人员在岗在位报警".equals(alarm.getModule())) {
                convertHandleAlarmData(alarm, areaMessageList);
            } else if ("作业票报警".equals(alarm.getModule())) {
                convertHandleAlarmData(alarm, jobMessageList);
            } else if ("车辆报警".equals(alarm.getModule())) {
                convertHandleAlarmData(alarm, carMessageList);
            }
        }
        try {
            handlingHazardAlarms(mhList);
            if (riskList.size() > 0) {
                log.info("批量报警信息处理：riskList {}", JSON.toJSONString(riskList));
                riskEvaluationAlarmMesageDao.saveAll(riskList);
                monitorPointDataWebSocketService.getDistrictAlarmMessage(riskList, "HANDLE");
                monitorPointDataWebSocketService.getDistrictAlarmMessage(riskList, "ADD");
            }
            //AI报警以及巡检排查报警不走异步
            if (inspectList.size() > 0) {
                log.info("批量报警信息处理：inspectList {}", JSON.toJSONString(inspectList));
                //同步流程引擎2.x隐患排查报警
                if (this.syncWorkFlow(inspectList)) {
                    inspectExceptionAlarmMesageService.updateBatchById(inspectList);
                    monitorPointDataWebSocketService.getInspectAlarmMessage(inspectList, "HANDLE", Context.getCurrentTenantId(), Context.getCurrentOrgCode());
                    monitorPointDataWebSocketService.getInspectAlarmMessage(inspectList, "ADD", Context.getCurrentTenantId(), Context.getCurrentOrgCode());
                }
            }
            //AI报警
            if (alarmMessageList.size() > 0) {
                log.info("批量AI报警信息处理：alarmMessageList{}", JSON.toJSONString(alarmMessageList));
                alarmMessageService.updateBatchById(alarmMessageList);
                monitorPointDataWebSocketService.getAIAlarmMessage(alarmMessageList, "HANDLE", Context.getCurrentTenantId(), Context.getCurrentOrgCode());
                monitorPointDataWebSocketService.getAIAlarmMessage(alarmMessageList, "ADD", Context.getCurrentTenantId(), Context.getCurrentOrgCode());
            }
            //区域人员报警
            if (areaMessageList.size() > 0) {
                log.info("区域人员报警信息处理：areaMessageList{}", JSON.toJSONString(areaMessageList));
                alarmMessageService.updateBatchById(areaMessageList);
                List<Long> ids = areaMessageList.stream().map(m -> Long.parseLong(m.getEmployeeId())).distinct().collect(Collectors.toList());
                orientationDataSyncService.renewLocateAlarmData(tenentId, orgCode, "pageAreaAlarm");
                orientationDataSyncService.pageSolveAlarm(new OrientationSearchBean(ids, "solveAreaAlarm", areaMessageList.get(0).getHandleInfo()));
            }
            //作业报警
            if (jobMessageList.size() > 0) {
                log.info("区域人员报警信息处理：jobMessageList{}", JSON.toJSONString(jobMessageList));
                alarmMessageService.updateBatchById(jobMessageList);
                List<Long> ids = jobMessageList.stream().map(m -> Long.parseLong(m.getEmployeeId())).distinct().collect(Collectors.toList());
                orientationDataSyncService.renewLocateAlarmData(tenentId, orgCode, "pageCertificateAlarm");
                orientationDataSyncService.pageSolveAlarm(new OrientationSearchBean(ids, "solveCertificateAlarm", jobMessageList.get(0).getHandleInfo()));
            }
            //车辆报警
            if (carMessageList.size() > 0) {
                log.info("区域人员报警信息处理：carMessageList{}", JSON.toJSONString(carMessageList));
                alarmMessageService.updateBatchById(carMessageList);
                List<Long> ids = carMessageList.stream().map(m -> Long.parseLong(m.getEmployeeId())).distinct().collect(Collectors.toList());
                orientationDataSyncService.renewLocateAlarmData(tenentId, orgCode, "pagCarAlarm");
                orientationDataSyncService.pageSolveAlarm(new OrientationSearchBean(ids, "solveCarAlarm", carMessageList.get(0).getHandleInfo()));
            }
            //更新定位报警列表 报警总数
            orientationDataSyncService.renewAlarmCount(Context.getCurrentTenantId(), Objects.requireNonNull(Context.getCompanyCode()).substring(0, 7));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public boolean syncWorkFlow(List<InspectExceptionAlarmMesage> inspectList) {
        if (CollectionUtils.isEmpty(inspectList)) {
            return true;
        }
        Long tenentId = inspectList.get(0).getTenentId();
        String orgCode = inspectList.get(0).getOrgCode();
        BaseConfig alarmConfig = baseConfigService.findConfig(BaseConfigCodes.OPEN_HD_TIME_OUT_GRADE_ALARM);
        BaseConfig defKeyConfig = baseConfigService.findConfig(BaseConfigCodes.YH_TimeOut_ProcessDefKey);
        if (alarmConfig == null || !COMMON_SWITCH_ON.equals(alarmConfig.getValue()) || defKeyConfig == null || StringUtils.isBlank(defKeyConfig.getValue())) {
            return true;
        }
        //组装header
        Map<String, String> header = this.getHeader(orgCode, tenentId);
        //获取url
        String url = this.getInspectAlarmUrl();
        Set<String> procInstIds = new HashSet<>();
        for (InspectExceptionAlarmMesage alarm : inspectList) {
            if (alarm.getProcInstId() != null) {
                procInstIds.add(alarm.getProcInstId());
            }
        }
        if (CollectionUtils.isEmpty(procInstIds)) {
            return true;
        }
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("processInstanceIds", procInstIds);
        requestBody.put("processDefinitionKey", defKeyConfig.getValue());
        String resp = HttpRequest.post(url).headerMap(header, false).body(JSONUtil.toJsonStr(requestBody)).execute().body();
        JSONObject respBody = JSONObject.parseObject(resp);
        if (!String.valueOf(respBody.get(ATTRIBUTE_CODE)).equals(BaseConfigCodes.MH_GRADING_ALARM_CODE)) {
            log.error("处理巡检报警{}同步失败:{}", procInstIds, JSONUtil.toJsonStr(respBody));
            return false;
        }
        return true;
    }

    private String getInspectAlarmUrl() {
        BaseConfig addressConfig = baseConfigService.getBaseConfigFromRedis(BaseConfigCodes.WORKFLOW_IP_ADDRESS);
        if (addressConfig == null || StringUtils.isBlank(addressConfig.getValue())) {
            return DEFAULT_WF_IP_ADDR + DEFAULT_WF_INSPECT_ALARM_URL;
        }
        return addressConfig.getValue() + DEFAULT_WF_INSPECT_ALARM_URL;
    }

    private Map<String, String> getHeader(String orgCode, Long tenentId) {
        BaseConfig appId = baseConfigService.getBaseConfigFromRedis(BaseConfigCodes.APPID);
        BaseConfig signature = baseConfigService.getBaseConfigFromRedis(BaseConfigCodes.SIGNATURE);
        Map<String, String> header = new HashMap<>();
        header.put("app-id", appId.getValue());
        header.put("org-code", orgCode);
        header.put("tenant-id", String.valueOf(tenentId));
        header.put("signature", signature.getValue());
        header.put("user-id", String.valueOf(9784)); //目前先写死
        header.put("user-name", "管理员"); //目前先写死
        return header;
    }

    private void convertHandleAlarmData(AlarmProcessBean alarm, List<AlarmMessage> list) {
        AlarmMessage message = alarmMessageService.getMessageById(alarm.getId());
        if (null != message) {
            message.setStatus(1);
            if (alarm.getHandleFlag() == 0) {
                message.setHandleInfo(alarm.getMsg());
            } else {
                message.setHandleInfo("已忽略");
            }
            message.setReason(alarm.getAlarmReason());
            //处理人待定
            message.setHandlerBy(alarm.getHandleBy().toString());
            message.setHandleTime(DateTime.now());
            list.add(message);
        }
    }

    @Override
    public void handlingHazardAlarms(List<MhAlarmMessage> mhList) {
        if (CollectionUtils.isEmpty(mhList)) {
            return;
        }
        log.info("批量报警信息处理：mhList {}", JSON.toJSONString(mhList));
        mhAlarmMessageDao.saveAll(mhList);
        monitorPointDataWebSocketService.getPointAlarmMessage(mhList, "HANDLE");
        monitorPointDataWebSocketService.getPointAlarmMessage(mhList, "ADD");
        //推送声光报警器调用中间件 : 重大危险源报警全部处理完成
        int count = mhAlarmMessageDao.countByStateIn();
        if (count == 0) {
            customAlarmMessageService.send(mhList.get(0), 0);
        } else {
            log.info("重大危险源还有{} 条报警，声光报警继续报警", count);
        }
        List<String> taskCodes = mhList.stream().map(e -> e.getId().toString()).collect(Collectors.toList());
        List<RiskDynamicRecord> records = riskDynamicRecordService.findAllByTaskCodesAndRiskType(taskCodes, 0);
        if (!CollectionUtils.isEmpty(records)) {
            for (RiskDynamicRecord record : records) {
                record.setStatus(1);
                record.setUpdateBy(Context.getCurrentUserId());
                record.setUpdateTime(new Date());
            }
            riskDynamicRecordService.saveOrUpdateBatch(records);
            riskEvaluationBusinessService.editDynamicDistrictLevel(records, "重大危险源报警");
        }
    }

    @Override
    public Optional<MhAlarmMessage> findById(Long id) {
        return mhAlarmMessageDao.findById(id);
    }

    private void getAirList(MajarHazardRealtimeDataMonitoringBean result, List<MhMonitoringPoint> airPoints) {

    }

    /**
     * 大屏-重大危险源监测数据
     *
     * @return
     */
    @Override
    public MajarHazardRealtimeDataMonitoringBean majorHazardRealtimeData(Integer pageNumber, Integer pageSize) {
        MajarHazardRealtimeDataMonitoringBean result = new MajarHazardRealtimeDataMonitoringBean();
        //危险源
        List<MhMajorHazard> allMh = majorHazardDao.findAll();
        if (!CollectionUtils.isEmpty(allMh)) {
            for (MhMajorHazard mh : allMh) {
                result.addDanger(convertMa(mh));
            }
            sortDanderList(result.getDangerList());
        }
        // 有毒可燃气体
        List<MhMonitoringPoint> airPoints = monitoringPointDao.getEnvironmentPoints(1L);
        if (!CollectionUtils.isEmpty(airPoints)) {
            List<MonitorPointData> realTimeVals = monitorPointDataService.getRealTimeVals(Context.getCurrentTenantId(), Context.getCompanyCode(), airPoints.stream().map(MhMonitoringPoint::getPointCode).collect(Collectors.toList()));
            Map<String, Double> pvMap = null;
            if (!CollectionUtils.isEmpty(realTimeVals)) {
                pvMap = realTimeVals.stream().collect(Collectors.toMap(MonitorPointData::getPointCode, MonitorPointData::getValue));
            }
            List<Long> pointIds = airPoints.stream().map(MhMonitoringPoint::getId).collect(Collectors.toList());
            List<AlarmMessageCountBean> messageCountList = alarmMapper.countByMhPointIdsAndStateNotEq(pointIds, 2);
            Map<Long, Integer> messageCountMap = CollectionUtil.isNotEmpty(messageCountList) ?
                    messageCountList.stream().collect(Collectors.toMap(AlarmMessageCountBean::getPointId, AlarmMessageCountBean::getCountNum))
                    : new HashMap<>();
            result.setAirList(this.getAirBeanList(airPoints, pvMap, messageCountMap));
//            for (MhMonitoringPoint p : airPoints) {
//                result.addAir(convertAir(p));
//            }
        }
//        this.getAirList(result, airPoints);
        //设备设施
//        List<BpDeviceFacilityCollection> facilities = getFacilitieList(pageNumber, pageSize, 0);
//        String orgCode = Context.getCompanyCode();
//        int number = bpDeviceFacilityCollectionDao.countNumber(orgCode);
//        if (!CollectionUtils.isEmpty(facilities)) {
//            for (BpDeviceFacilityCollection f : facilities) {
//                if ("独立库区".equals(f.getName()) && DeviceFacilityTypes.KU_QU.getName().equals(f.getDeviceTypeName())
//                        || DeviceFacilityTypes.GONG_YI_LIU_CHENG.getName().equals(f.getDeviceTypeName())) {
//                    // 忽略独立库区和工艺流程
//                    number = number - 1;
//                } else {
//                    result.addFacility(convert(f));
//                }
//            }
//            sortFacilities(result.getFacilityList());
//        }
        //仓库
//        List<BpStoreHouse> houses = bpStoreHouseDao.findByTypeFlag(0);
        List<Long> ids = storeMapper.findByTypeFlag(0);
        List<BpStoreHouseAddBean> hous = new ArrayList<>();
//        List<Long> ids = houses.stream().map(BpStoreHouse::getId).collect(Collectors.toList());
//        for (BpStoreHouse s : houses) {
//            BpStoreHouseAddBean hBean = bpStoreHouseService.getById(s.getId());
//            hous.add(hBean);
//        }
        if (!CollectionUtils.isEmpty(ids)) {
            hous = bpStoreHouseService.getByIds(ids);
            result.setStoreHouseList(hous);
        }
//        result.setFacilityTotalNumber(number);
        result.setCameraList(findAllCameras());
        long pointCount = mhMonitoringPointService.countAll();
        LambdaQueryWrapper<CustomizeMonitorPoint> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomizeMonitorPoint::getDeleteFlag, "0");
        long customizePointCount = customizeMonitorPointService.count(wrapper);
        result.setMonitorPointCount(pointCount + customizePointCount);
        return result;
    }

    //环境气体信息
    private List<AirMonitoringBean> getAirBeanList(List<MhMonitoringPoint> airPoints, Map<String, Double> pvMap, Map<Long, Integer> messageCountMap) {
        List<AirMonitoringBean> airList = new ArrayList<>();
        for (MhMonitoringPoint p : airPoints) {
            AirMonitoringBean fb = new AirMonitoringBean();
            fb.setName(p.getName());
            fb.setId(p.getId());
            //状态 0正常,1,异常,2未连接
            Integer state = null;
            if (p.getState() != null && p.getState() == 1) {
                if (p.getSwitchs() != null) {
                    if (p.getSwitchs().equals("1")) {
                        state = 0;
                    }
                    if (p.getSwitchs().equals("0")) {
                        state = 0;
                    }
                } else {
                    if (pvMap != null && pvMap.get(p.getPointCode()) != null) {
                        state = 2;
                    } else {
                        state = 0;
                    }
                }
            } else {
                state = 2;
            }
            Integer count = messageCountMap.get(p.getId());
            airList.add(this.createAirBean(p, fb, state, count));
        }
        return airList;
    }

    private AirMonitoringBean createAirBean(MhMonitoringPoint p, AirMonitoringBean fb, Integer state, Integer count) {
        Integer flag;
        if (count != null) {
            flag = this.getAlarmFlagYou(count);
        } else {
            flag = this.getAlarmFlag(p);
        }
        if (flag == 1) {
            state = 1;
        }
        if (p.getMhMonitoringType() != null) {
            fb.setType(p.getMhMonitoringType().getName());
            if (p.getMhMonitoringType().getCategoryId() != null && p.getMhMonitoringType().getCategoryId().equals(1L)) {
                fb.setImageId(p.getMhMonitoringType().getImageId());
                if (p.getMhMonitoringType().getImageId() != null) {
                    fb.setDownloadUrl(serverUrl + "/image/view?id=" + p.getMhMonitoringType().getImageId());
                }
            }
            //监测点类型 编号
            fb.setPointCode(p.getPointCode());
            fb.setPointTypeCode(p.getMhMonitoringType().getCode());
            fb.setPointTypeName(p.getMhMonitoringType().getName());
        }
        fb.setStatus(state);
        String location = p.getLocation();
        if (location != null) {
            MapUtils.WwytPoint point = MapUtils.parseSinglePoint(location);
            if (point != null && point.getX() != null && point.getY() != null) {
                fb.setX(point.getX());
                fb.setY(point.getY());
                fb.setZ(point.getZ() == null ? 0.00 : point.getZ());
                fb.setLocation(location);
            }
        }
        return fb;
    }

    /**
     * @param pageNumber
     * @param pageSize
     * @param excludeType 0 所有 1除去库房的设备设施 2 除去库房的所有设备设施
     * @return
     */
    private List<BpDeviceFacilityCollection> getFacilitieList(Integer pageNumber, Integer pageSize, Integer excludeType) {
        //设备设施
        String orgCode = Context.getCompanyCode();
        if ((pageNumber == null || pageNumber < 0)) {
            pageNumber = 0;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 100;
        }
        List<BpDeviceFacilityCollection> facilities = new ArrayList<>();
        if (excludeType.intValue() == 0) {
            facilities = bpDeviceFacilityCollectionDao.getListBySize(pageNumber * pageSize, pageSize, orgCode);
        } else if (excludeType.intValue() == 1) {
            facilities = bpDeviceFacilityCollectionDao.getListBySizeAndExcludeType(pageNumber * pageSize, pageSize, orgCode);
        } else if (excludeType.intValue() == 2) {
            facilities = bpDeviceFacilityCollectionDao.getAllFacillityAndExcludeType(orgCode);
        }

        return facilities;
    }

    /**
     * 大屏-设备设施详情
     *
     * @param id
     * @return
     */
    @Override
    public DeviceFacilityStatusBean getDeviceFacilityStatusBean(Long id) {
        BpDeviceFacilityCollection device = facilityService.findById(id);
        if (device == null) {
            return null;
        }
        List<BpDeviceFacilityMonitoringPoint> fmps = bpDeviceFacilityMonitoringPointDao.findByDeviceId(device.getId());
//        Set<MhMonitoringPoint> mhMonitoringPoints = device.getMhMonitoringPoints();
        FacilityDetailBean b = new FacilityDetailBean();
        b.setId(id);
        b.setName(device.getName());
        if (device.getDeviceId() != null) {
            Optional<BpProductionFacility> obf = bpProductionFacilityDao.findById(device.getDeviceId());
            if (obf.isPresent()) {
                b.setStateName(ProductionFacilityStates.findNameById(obf.get().getState()));
            }
        }
        if ("生产装置".equals(device.getDeviceTypeName())) {
            BpProductionFacility facility = facilityDao.getOne(device.getDeviceId());
            b.setModel(facility.getEquipmentModel());
            b.setStatus(ProductionFacilityStates.findNameById(facility.getState()));
            b.setDepartName(facilityDao.findDepartNameById(device.getDeviceId()));
        }
        b.setImportant("Y".equals(device.getKeyEquipment()));
        // 设备类型
        b.setType(device.getDeviceTypeName());
        b.setNumber(device.getCode());
        //危险单元
        if (device.getMajorHazardId() != null) {
            b.setUnit(getMajorHazardName(device.getMajorHazardId()));
        } else {
            //从设施表中找
            b.setUnit(findMajorHazardInfoOfDevice(device));
        }
        DeviceFacilityStatusBean re = new DeviceFacilityStatusBean();
        re.setDeviceList(b);
        if (!CollectionUtils.isEmpty(fmps)) {
            List<MonitoringPointValueBean> list = convertMonitoringPointsValue(fmps);
            re.setMonitorList(list);
        }

        List<Long> facilityVideoIds = productionFacilityVideoDao.findByFacilityId(device.getDeviceId());
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(facilityVideoIds)) {
            List<BpSystemVideo> videoList = bpSystemVideoDao.findByIds(facilityVideoIds);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(videoList)) {
                List<BpSystemVideoAddBean> beans = new ArrayList<>();
                for (BpSystemVideo bpSystemVideo : videoList) {
                    BpSystemVideoAddBean videoAddBean = new BpSystemVideoAddBean();
                    BeanUtils.copyProperties(bpSystemVideo, videoAddBean);
                    videoAddBean.setDateFormat("yyyy-MM-dd");
                    videoAddBean.setTimeFormat("mm:HH:dd");
                    if (StringUtils.isNotBlank(bpSystemVideo.getEvaluation())) {
                        Optional<RiskDistrict> districtOperation = districtDao.findById(new Long(bpSystemVideo.getEvaluation()));
                        districtOperation.ifPresent(riskDistrict -> videoAddBean.setEvaluationName(riskDistrict.getName()));
                        videoAddBean.setEvaluationId(bpSystemVideo.getEvaluation());
                    }
                    beans.add(videoAddBean);
                }
                re.setVideoList(beans);
            }
        }
        return re;
    }

    /**
     * 大屏-风险四色图列表
     *
     * @param page
     * @param condition
     * @return
     */
    @Override
    public ResultBean centerRiskDistrictPage(Pageable page, CenterRiskDistrictSearchBean condition) {
        List<RiskDistrict> list = districtDao.getDistrictByCondition(condition.getDistrictName(), condition.getRiskLevel());
        if (CollectionUtils.isEmpty(list)) {
            return ResultBean.success(new ArrayList<>());
        }
        list = list.stream()
                .sorted(Comparator.comparing(RiskDistrict::getRiskLevel, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        List<DistrictInfoBean> collect = new ArrayList<>();
        RiskEvaluationControl control = controlDao.findByName("风险四色图计算逻辑");
        for (RiskDistrict district : list) {
            DistrictInfoBean districtInfoBean = convertToDistrictInfoBean(district);
            int count = bpWorkSafetyCertDao.countByRiskDistrickId(district.getId());
            districtInfoBean.setWorkCount(count);
            Integer level = null;
            int risingMark = 0;
            if (control != null && control.getSwitchState() == 0) {
                level = district.getStableRiskLevel();
            } else {
                if (district.getRealTimeRiskLevel() != null) {
                    level = RiskLevels.getRealLevelIntValue(district.getRealTimeRiskLevel());
                    if (level > 4) {
                        level = 4;
                    } else if (level < 1) {
                        level = 1;
                    }
                }
                if (level != null && district.getRiskLevel() != null) {
                    if (level < district.getRiskLevel()) {
                        risingMark = 1;
                    }
                }
            }
            districtInfoBean.setRisingMark(risingMark);
            districtInfoBean.setLevel(level);
            collect.add(districtInfoBean);
        }
        collect = PageableUtil.getList(page.getPageNumber(), page.getPageSize(), collect);
        return ResultBean.pageData(collect, list.size());
    }

    /**
     * 大屏-重大危险源监测预警列表
     *
     * @param page
     * @param condition
     * @return
     */
    @Override
    public ResultBean centerMajorHazardPage(Pageable page, CenterMajorHazardSearchBean condition) {
        //:1重大危险源;2设备装置;3有毒可燃气体;4视频监控
        if (condition.getFlag() == null) {
            return ResultBean.success(new ArrayList<>());
        } else if (condition.getFlag().intValue() == 1) {
            return getMajorHazardPage(page, condition);
        } else if (condition.getFlag().intValue() == 2) {
            return getFacilityPage(page, condition);
            //2.3环境监测点用code区分
        } else if (StringUtils.isNotBlank(condition.getPointTypeCode())) {
            return getAirPage(page, condition);
        } else if (condition.getFlag().intValue() == 4) {
            return getCameraPage(page, condition);
        } else {
            return ResultBean.success(new ArrayList<>());
        }
    }

    /**
     * 大屏-重大危险源监测预警类型列表
     *
     * @return
     */
    @Override
    public List<SimpleSelectListBean> getCenterMajorHazardTypeList() {
        List<SimpleSelectListBean> list = new ArrayList<>();
        SimpleSelectListBean bean1 = new SimpleSelectListBean();
        SimpleSelectListBean bean2 = new SimpleSelectListBean();
        SimpleSelectListBean bean3 = new SimpleSelectListBean();
        SimpleSelectListBean bean4 = new SimpleSelectListBean();
        bean1.setValue(1L);
        bean2.setValue(2L);
        bean3.setValue(3L);
        bean4.setValue(4L);
        bean1.setLabel("重大危险源");
        bean2.setLabel("设备装置");
        bean3.setLabel("有毒可燃气体");
        bean4.setLabel("视频监控");
        list.add(bean1);
        list.add(bean2);
        list.add(bean3);
        list.add(bean4);
        return list;
    }

    /**
     * 大屏-风险四色图风险等级列表
     *
     * @return
     */
    @Override
    public List<SimpleSelectListBean> getRiskDistrictLevelList() {
        List<SimpleSelectListBean> list = new ArrayList<>();
        for (int i = 1; i < RiskLevels.values().length; i++) {
            SimpleSelectListBean bean = new SimpleSelectListBean();
            bean.setValue(Long.valueOf(i));
            bean.setLabel(RiskLevels.findRiskNameByCode(i));
            list.add(bean);
        }
        return list;
    }

    @Override
    public ResultBean workFlowScreen(WorkFlowSearchBean searchMap) {
        return workFlowProcessService.workFlowScreen(searchMap);
    }

    @Override
    public ResultBean allColumn() {
        List<ScreenColumnBean> list = Lists.newArrayList();
        list.add(new ScreenColumnBean(null, "重大危险源", null));
        list.add(new ScreenColumnBean(null, "风险四色图", null));
        list.add(new ScreenColumnBean(null, "人车管控", null));
        //获取所有启用位置服务
        List<ScreenColumnBean> columnList = workFlowProcessService.allColumn();
        list.addAll(columnList);
        return ResultBean.success(list);
    }

    /**
     * 获取大屏分类列表
     *
     * @return
     */
    @Override
    public ResultBean getAllColumn() {
        List<WorkFlowScreenType> all = workFlowScreenTypeDao.findAll();
        List<ScreenColumnBean> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(all)) {
            for (WorkFlowScreenType type : all) {
                ScreenColumnBean bean = new ScreenColumnBean();
                bean.setTypeId(type.getId());
                bean.setTypeName(type.getTypeName());
                bean.setCode(type.getCode());
                list.add(bean);
            }

        }
        return ResultBean.success(list);
    }

    /**
     * 获取大屏分类列表及所属子表
     *
     * @return
     */
    @Override
    public ScreenTypeAndConfigBean getScreenTypeList() {
        ScreenTypeAndConfigBean bean = new ScreenTypeAndConfigBean();
        List<ScreenTypeListBean> beanList = new ArrayList<>();
        //1.查询所有显示的类型
        List<WorkFlowScreenType> typeList = workFlowScreenTypeDao.findByIsShowAndShowNumberDesc();
        if (!CollectionUtils.isEmpty(typeList)) {
            List<Long> ids = typeList.stream().map(r -> r.getId()).collect(Collectors.toList());
            List<Integer> types = new ArrayList<>();
            types.add(MonitorTypeEnum.TOXIC_GAS.getValue());
            types.add(MonitorTypeEnum.CUSTOM.getValue());
            List<WorkFlowScreenConfig> workFlowScreenConfigs = workFlowScreenConfigDao.findBizTypeNameListByTypeIdsAndEnvironmentPointFlag(ids, types);
            Map<Long, List<WorkFlowScreenConfig>> map = new HashMap<>();
            if (!CollectionUtils.isEmpty(workFlowScreenConfigs)) {
                for (WorkFlowScreenConfig workFlowScreenConfig : workFlowScreenConfigs) {
                    if (map.get(workFlowScreenConfig.getTypeId()) != null) {
                        List<WorkFlowScreenConfig> configs = map.get(workFlowScreenConfig.getTypeId());
                        configs.add(workFlowScreenConfig);
                    } else {
                        List<WorkFlowScreenConfig> configs = new ArrayList<>();
                        configs.add(workFlowScreenConfig);
                        map.put(workFlowScreenConfig.getTypeId(), configs);
                    }
                }
            }

            for (WorkFlowScreenType type : typeList) {
                ScreenTypeListBean screenTypeListBean = new ScreenTypeListBean();
                screenTypeListBean.setTypeId(type.getId());
                screenTypeListBean.setTypeName(type.getTypeName());
                screenTypeListBean.setTypeCode(type.getCode());
                screenTypeListBean.setUrl(type.getUrl());
                //有毒可燃气体大屏配置
//                List<Integer> types = new ArrayList<>();
//                types.add(MonitorTypeEnum.TOXIC_GAS.getValue());
//                types.add(MonitorTypeEnum.CUSTOM.getValue());
//                List<WorkFlowScreenConfig> pointConfigs = workFlowScreenConfigDao.findBizTypeNameListByTypeIdAndEnvironmentPointFlag(type.getId(), types);
                List<WorkFlowScreenConfig> pointConfigs = map.get(type.getId());
                //流程大屏配置
                List<String> bizNameList = workFlowScreenConfigDao.findBizTypeNameListByTypeIdAndEnvironmentFlagIsNull(type.getId());
                List<ScreenTypeListSonBean> sons = new ArrayList<>();
                if (!CollectionUtils.isEmpty(pointConfigs)) {
                    for (WorkFlowScreenConfig pointConfig : pointConfigs) {
                        ScreenTypeListSonBean son = new ScreenTypeListSonBean();
                        son.setBizTypeName(pointConfig.getBizTypeName());
                        son.setPointTypeCode(pointConfig.getBizTypeCode());
                        son.setEnvironmentPointFlag(pointConfig.getEnvironmentPointFlag());
                        if (pointConfig.getEnvironmentPointFlag() != null && pointConfig.getEnvironmentPointFlag().equals(1)) {
                            son.setEnvironmentPointFlagName("是");
                        } else if (MonitorTypeEnum.CUSTOM.getValue().equals(pointConfig.getEnvironmentPointFlag())) {
                            son.setEnvironmentPointFlagName(MonitorTypeEnum.CUSTOM.getDesc());
                        } else {
                            son.setEnvironmentPointFlagName("否");
                        }
                        sons.add(son);
                    }
                }
                for (String bizTypeName : bizNameList) {
                    ScreenTypeListSonBean son = new ScreenTypeListSonBean();
                    son.setBizTypeName(bizTypeName);
                    son.setEnvironmentPointFlag(0);
                    son.setEnvironmentPointFlagName("否");
                    sons.add(son);
                }
                screenTypeListBean.setSons(sons);
                beanList.add(screenTypeListBean);
            }
        }
        bean.setBeanList(beanList);
        //2.地图配置
        Map<Long, WorkFlowLocationConfigBean<WorkFlowScreenConfigBean, WorkFlowRailAlarmConfigBean>> map = new HashMap<>();
        List<String> names = workFlowScreenConfigDao.getAllBizTypeName();
        if (!org.apache.shiro.util.CollectionUtils.isEmpty(names)) {
            List<WorkFlowProcess> processList = workFlowProcessDao.findByBizTypeNames(names);
            if (!CollectionUtils.isEmpty(processList)) {
                List<Long> processIds = processList.stream().map(r -> r.getId()).collect(Collectors.toList());
                map = workFlowProcessService.getLocationConfigMapByProcessIds(processIds);
//                for (WorkFlowProcess process : processList) {
//                    WorkFlowLocationConfigBean<WorkFlowScreenConfigBean, WorkFlowRailAlarmConfigBean> configBean = workFlowProcessService.getLocationConfigByProcessId(process.getId());
//                    if (configBean != null) {
//                        map.put(process.getId(), configBean);
//                    }
//                }
            }
        }
        bean.setMap(map);
        return bean;
    }

    /**
     * 大屏获取所有勾选专栏配置
     *
     * @return
     */
    @Override
    public List<ScreenConfigListBean> getScreenAllConfigList(Long typeId) {
        //获取固定的和流程上得到的配置 -bizTypeName不可以重复
        List<ScreenConfigListBean> list = this.getProcessConfigBeanList();
        //环境气体配置-bizTypeName可以重复
        List<ScreenConfigListBean> envConfigBeans = this.getPointTypeConfigBeanList();
        if (!CollectionUtils.isEmpty(envConfigBeans)) {
            list.addAll(envConfigBeans);
        }
        //typeId 不为空 查询专栏下对应的显示配置
        if (typeId != null) {
            Optional<WorkFlowScreenType> owt = workFlowScreenTypeDao.findById(typeId);
            if (owt.isPresent()) {
                WorkFlowScreenType type = owt.get();
                if (StringUtils.isNotBlank(type.getScreenJson())) {
                    ScreenConfigListReturnBean rb = JSONObject.parseObject(type.getScreenJson(), ScreenConfigListReturnBean.class);
                    if (rb != null && !CollectionUtils.isEmpty(rb.getBeanList())) {
                        List<ScreenConfigListBean> typeList = rb.getBeanList();
                        for (int i = 0; i < list.size(); i++) {
                            ScreenConfigListBean configBean = list.get(i);
                            for (int j = 0; j < typeList.size(); j++) {
                                ScreenConfigListBean typeBean = typeList.get(j);
                                if (configBean.getId().equals(typeBean.getId())) {
                                    //赋予专栏配置的属性
                                    BeanUtils.copyProperties(typeBean, configBean, "showOrder", "bizTypeName", "typeCode" +
                                            "", "environmentPointFlagName");
                                    continue;
                                }
                            }
                        }
                    }
                }
            }
        }
        list = list.stream().sorted(Comparator.comparing(ScreenConfigListBean::getShowOrder, Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        return list;
    }

    /**
     * 获取固定的和流程上得到配置
     *
     * @return
     */
    private List<ScreenConfigListBean> getProcessConfigBeanList() {
        List<ScreenConfigListBean> list = new ArrayList<>();
        List<WorkFlowScreenConfig> all = workFlowScreenConfigDao.findAllByEnviromentFlag(0);
        int flag = 0;
        for (WorkFlowScreenConfig config : all) {
            ScreenConfigListBean bean = new ScreenConfigListBean();
            BeanUtils.copyProperties(config, bean);
            if (config.getBizTypeName() == null) {
                if (config.getProcessId() != null) {
                    Optional<WorkFlowProcess> owp = workFlowProcessDao.findById(config.getProcessId());
                    if (owp.isPresent()) {
                        WorkFlowProcess process = owp.get();
                        if (!process.getLocationServiceOpen()) {
                            flag = 1;
                        }
                        if (StringUtils.isNotBlank(process.getBizTypeName())) {
                            bean.setBizTypeName(process.getBizTypeName());
                        } else if (StringUtils.isNotBlank(process.getBizTypeName())) {
                            bean.setBizTypeName(process.getBizName());
                        }
                    }
                }
            }
            if (flag == 0) {
                bean = this.config2Bean(config, bean);
                list.add(bean);
            }
            flag = 0;
        }
        //去除多余的bizTypeName
        if (!CollectionUtils.isEmpty(list)) {
            list = list.stream()
                    .filter(c -> StringUtils.isNotBlank(c.getBizTypeName()))
                    .collect(Collectors.collectingAndThen(Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(ScreenConfigListBean::getBizTypeName))), ArrayList::new));
        }
        return list;
    }

    /**
     * 获取环境监测点类型配置
     *
     * @return
     */
    private List<ScreenConfigListBean> getPointTypeConfigBeanList() {
        List<Integer> types = new ArrayList<>();
        types.add(MonitorTypeEnum.TOXIC_GAS.getValue());
        types.add(MonitorTypeEnum.CUSTOM.getValue());
        List<WorkFlowScreenConfig> envConfigs = workFlowScreenConfigDao.findAllByEnviromentFlagList(types);
        List<ScreenConfigListBean> envConfigBeans = new ArrayList<>();
        if (!CollectionUtils.isEmpty(envConfigs)) {
            for (WorkFlowScreenConfig config : envConfigs) {
                ScreenConfigListBean bean = new ScreenConfigListBean();
                BeanUtils.copyProperties(config, bean);
                bean = this.config2Bean(config, bean);
                envConfigBeans.add(bean);
            }

        }
        return envConfigBeans;
    }

    /**
     * 大屏按钮显示
     *
     * @param config
     * @param bean
     * @return
     */
    private ScreenConfigListBean config2Bean(WorkFlowScreenConfig config, ScreenConfigListBean bean) {
        //判断是否是环境监测点
        if (config.getEnvironmentPointFlag() != null && config.getEnvironmentPointFlag().equals(1)) {
            bean.setEnvironmentPointFlagName("是");
        } else if (MonitorTypeEnum.CUSTOM.getValue().equals(config.getEnvironmentPointFlag())) {
            bean.setEnvironmentPointFlagName(MonitorTypeEnum.CUSTOM.getDesc());
        } else {
            bean.setEnvironmentPointFlagName("否");
        }
        if (config.getShow() == null || config.getShow().intValue() == 0) {
            bean.setShow(false);
        } else {
            bean.setShow(true);
        }

        if (config.getValueShow() == null || config.getValueShow().intValue() == 0) {
            bean.setValueShow(false);
        } else {
            bean.setValueShow(true);
        }

        if (config.getValueShowButton() == null || config.getValueShowButton().intValue() == 0) {
            bean.setValueShowButton(false);
        } else {
            bean.setValueShowButton(true);
        }

        if (config.getTypeId() != null) {
            String code = workFlowScreenTypeDao.getCodeById(config.getTypeId());
            bean.setTypeCode(code);
        }
        return bean;
    }


    /**
     * 修改大屏勾选栏配置
     *
     * @param returnBean
     * @return
     */
    @Override
    public ResultBean screenColumnSave(ScreenConfigListReturnBean returnBean) {
        if (!CollectionUtils.isEmpty(returnBean.getBeanList())) {
            Optional<WorkFlowScreenType> owt = workFlowScreenTypeDao.findById(returnBean.getTypeId());
            if (owt.isPresent()) {
                WorkFlowScreenType type = owt.get();
                type.setScreenJson(JSONObject.toJSONString(returnBean));
                workFlowScreenTypeDao.save(type);
            }

        }
        return ResultBean.defaultSuccessResult();
    }

    /**
     * 批量处理所有报警
     *
     * @param bean
     */
    @Override
    public void processAlarmBatchAll(CenterAlarmMessageHandlerBean bean) {
        //危险源报警:备注  风险分区报警:处理说明
        if (!(bean.getHandleFlag() != null && bean.getHandleFlag().intValue() == 0)) {
            bean.setMsg("已忽略");
        }
        log.info("报警信息全部处理：CenterAlarmMessageHandlerBean:{}", JsonUtil.toJson(bean));
        //处理人
        if (bean.getHandleBy() == null) {
            bean.setHandleBy(Context.getCurrentUserId());
            log.info("报警信息全部处理添加处理人：CenterAlarmMessageHandlerBean:{}", JsonUtil.toJson(bean));
        }
        try {
            Long tenentId = Context.getCurrentTenantId();
            String orgCode = Context.getCompanyCode();
            if (bean.getType() != null && bean.getType().intValue() == 0) {
                mhAlarmMessageDao.setAllMeaageHandled(bean.getMsg(), bean.getAlarmReason(), baseUserDao.getRealNameById(bean.getHandleBy()), LocalDateTime.now());
                monitorPointDataWebSocketService.getPointAlarmMessage(null, "HANDLE_ALL");
                // 声光报警器
                MhAlarmMessage message = new MhAlarmMessage();
                message.setTenentId(Context.getCurrentTenantId());
                message.setOrgCode(Context.getCompanyCode());
                List<RiskDynamicRecord> records = riskDynamicRecordService.findAllByRiskType(0);
                if (!CollectionUtils.isEmpty(records)) {
                    for (RiskDynamicRecord record : records) {
                        record.setStatus(1);
                        record.setUpdateTime(new Date());
                    }
                    riskDynamicRecordService.saveOrUpdateBatch(records);
                    riskEvaluationBusinessService.editDynamicDistrictLevel(records, "重大危险源报警");
                }
                customAlarmMessageService.send(message, 0);
            } else if (bean.getType() != null && bean.getType().intValue() == 1) {
                riskEvaluationAlarmMesageDao.setAllMeaageHandled(bean.getMsg(), bean.getAlarmReason(), bean.getHandleBy(), new Date());
                monitorPointDataWebSocketService.getDistrictAlarmMessage(null, "HANDLE_ALL");
            } else if (bean.getType() != null && bean.getType().intValue() == 2) {
                List<InspectExceptionAlarmMesage> alarms = inspectExceptionAlarmMesageService.list(new LambdaQueryWrapper<InspectExceptionAlarmMesage>().eq(InspectExceptionAlarmMesage::getDeleteFlag, DeleteFlag.EFFECTIVE.getCode()).eq(InspectExceptionAlarmMesage::getState, 0).isNotNull(InspectExceptionAlarmMesage::getProcInstId));
                if (this.syncWorkFlow(alarms)) {
                    inspectExceptionAlarmMesageService.setAllMeaageHandled(bean.getMsg(), bean.getAlarmReason(), bean.getHandleBy(), new Date());
                    monitorPointDataWebSocketService.getInspectAlarmMessage(null, "HANDLE_ALL", tenentId, orgCode);
                }
            } else if (bean.getType() != null && bean.getType().intValue() == 3) {
                alarmMessageService.setAllMeaageHandled(bean.getMsg(), bean.getAlarmReason(), bean.getHandleBy(), new Date());
                monitorPointDataWebSocketService.getAIAlarmMessage(null, "HANDLE_ALL", tenentId, orgCode);
            } else if (bean.getType() != null && (bean.getType().intValue() == 4 || bean.getType().intValue() == 5 || bean.getType().intValue() == 6)) {
                Integer alarmType = 1;
                String flag = "";
                String saveFlag = "";
                if (bean.getType().intValue() == 4) {
                    alarmType = ApiAlarmTypeEnum.AREA_ALARM.getId();
                    flag = "pageAreaAlarm";
                    saveFlag = "solveAreaAlarm";
                } else if (bean.getType().intValue() == 5) {
                    alarmType = ApiAlarmTypeEnum.JOBA_LARM_EVENT.getId();
                    flag = "pageCertificateAlarm";
                    saveFlag = "solveCertificateAlarm";
                } else if (bean.getType().intValue() == 6) {
                    alarmType = ApiAlarmTypeEnum.ALARM_EVENT.getId();
                    flag = "pagCarAlarm";
                    saveFlag = "solveCarAlarm";
                }
                List<AlarmMessage> messages = alarmMessageService.findAllByAlarmTypeAndStatus(alarmType, 0, tenentId, orgCode);
                if (!CollectionUtils.isEmpty(messages)) {
                    convertMessageData(messages, bean);
                    alarmMessageService.updateBatchById(messages);
                    List<Long> ids = messages.stream().map(m -> Long.parseLong(m.getEmployeeId())).distinct().collect(Collectors.toList());
                    orientationDataSyncService.renewLocateAlarmData(tenentId, orgCode, flag);
                    orientationDataSyncService.pageSolveAlarm(new OrientationSearchBean(ids, saveFlag, bean.getMsg()));
                }
            }
            //更新报警总数
            orientationDataSyncService.renewAlarmCount(Context.getCurrentTenantId(), Context.getCompanyCode().substring(0, 7));
        } catch (Exception e) {
            log.info("报警一键处理", e);
        }
    }

    private void convertMessageData(List<AlarmMessage> messages, CenterAlarmMessageHandlerBean bean) {
        messages.forEach(m -> {
            m.setStatus(1);
            m.setHandleTime(new Date());
            m.setHandleInfo(bean.getMsg());
            m.setReason(bean.getAlarmReason());
            m.setHandlerBy(Context.getCurrentUserId().toString());
        });
    }

    /**
     * 工艺流程列表
     *
     * @param page
     * @param name
     * @return
     */
    @Override
    public ResultBean centerManuFacturingTechPage(Pageable page, String name) {
        List<BpManufacturingTech> all = bpManufacturingTechDao.findByNameOrderByIdDesc(name);
        List<CenterManuFacturingTechPageBean> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(all)) {
            List<BpManufacturingTech> btList = PageableUtil.getList(page, all);
            for (BpManufacturingTech b : btList) {
                CenterManuFacturingTechPageBean bean = new CenterManuFacturingTechPageBean();
                BeanUtils.copyProperties(b, bean);
                bean.setIsKeyMonitoringDangerTechName(BizUtils.translateYesNoToChinese(b.getIsKeyMonitoringDangerTech()));
                list.add(bean);
            }
        }
        return ResultBean.pageData(list, all.size());
    }

    /**
     * 工艺流程详情表
     *
     * @param id
     * @return
     */
    @Override
    public CenterManuFacturingTechBean getManuFacturingTechById(Long id) {
        CenterManuFacturingTechBean bean = new CenterManuFacturingTechBean();
        Optional<BpManufacturingTech> obt = bpManufacturingTechDao.findById(id);
        if (obt.isPresent()) {
            BpManufacturingTech tech = obt.get();
            BeanUtils.copyProperties(tech, bean);
            if (tech.getIsKeyMonitoringDangerTech() != null) {
                bean.setIsKeyMonitoringDangerTechName(BizUtils.translateYesNoToChinese(tech.getIsKeyMonitoringDangerTech()));
            }
            List<MonitoringPointValueBean> list = new ArrayList<>();
            List<BpMonitoringPointRel> pointRels = bpMonitoringPointRelDao.findByRefTypeAndRefId("manufacturing_tech",
                    tech.getId());
            if (!CollectionUtils.isEmpty(pointRels)) {
                for (BpMonitoringPointRel rel : pointRels) {
                    Optional<MhMonitoringPoint> omp = monitoringPointDao.findById(rel.getMonitoringPointId());
                    if (omp.isPresent()) {
                        list.add(getMonitoringPointValueBean(omp.get()));
                    }
                }
            }
            bean.setMonitoringPointBeans(list);
        }
        return bean;
    }

    /**
     * 获取危险源关联的预案列表
     *
     * @param hazardId
     * @return
     */
    @Override
    public List<CenterEmergencyPlanBean> getPlanListByHazardId(Long hazardId) {
        return planService.getPlanListByHazardId(hazardId);
    }

    /**
     * 大屏人员/承包商人员 帽子信息
     *
     * @return
     */
    @Override
    public List<ScreenPeopleCapBean> getScreenPeopleCaps() {
        List<ScreenPeopleCapBean> list = new ArrayList<>();
        List<BaseUser> userList = baseUserDao.findBySnAndLocateSync();
        List<BpContractorStaff> staffList = BpContractorStaffDao.findBySnAndLocateSync();
        if (!CollectionUtils.isEmpty(userList)) {
            for (BaseUser user : userList) {
                ScreenPeopleCapBean capBean = new ScreenPeopleCapBean();
                capBean.setSn(user.getSn());
                capBean.setPeopleType("user");
                capBean.setCapUrl(serverUrl + "/image/view?id=" + user.getCapId());
                list.add(capBean);
            }
        }
        if (!CollectionUtils.isEmpty(staffList)) {
            for (BpContractorStaff staff : staffList) {
                ScreenPeopleCapBean capBean = new ScreenPeopleCapBean();
                capBean.setSn(staff.getSn());
                capBean.setPeopleType("staff");
                capBean.setCapUrl(serverUrl + "/image/view?id=" + staff.getCapId());
                list.add(capBean);
            }
        }
        return list;
    }

    @Override
    public ResultBean getAllfacility() {
        List<FacilityMonitoringBean> beanList = new ArrayList<>();
        List<BpDeviceFacilityCollection> facilitieList = getFacilitieList(null, null, 2);
        if (!CollectionUtils.isEmpty(facilitieList)) {
            for (BpDeviceFacilityCollection collection : facilitieList) {
                beanList.add(convert(collection));
            }
            sortFacilities(beanList);
        }
        return ResultBean.success(beanList);
    }

    @Override
    public ResultBean columnList(ScreenColumnBean screenColumnBean) {
        return workFlowProcessService.columnList(screenColumnBean);
    }

    @Override
    public ResultBean columnSave(ScreenColumnConfigBean bean) {
        return workFlowProcessService.columnSave(bean);
    }

    /**
     * 大屏-重大危险源监测预警列表-摄像头
     *
     * @param page
     * @param condition
     * @return
     */
    private ResultBean getCameraPage(Pageable page, CenterMajorHazardSearchBean condition) {
        QBpSystemVideo video = QBpSystemVideo.bpSystemVideo;
        Predicate p = null;
        if (condition.getName() != null) {
            p = ExpressionUtils.and(p, video.name.contains(condition.getName()));
        }
        Page<BpSystemVideo> pageData = p == null ? bpSystemVideoDao.findAll(page) : bpSystemVideoDao.findAll(p, page);
        Page<CameraMonitoringBean> beanPage = getCameraBeanPage(pageData);
        return ResultBean.pageData(beanPage.getContent(), beanPage.getTotalElements());
    }

    private Page<CameraMonitoringBean> getCameraBeanPage(Page<BpSystemVideo> pageData) {
        return PageDataUtils.convertPageData(pageData, new PageDataUtils.PageDataConvert<CameraMonitoringBean, BpSystemVideo>() {
            @Override
            public CameraMonitoringBean convert(BpSystemVideo vs) {
                return convertCamerasBean(vs, null);
            }
        });
    }

    /**
     * 大屏-重大危险源监测预警列表-有毒可燃气体
     *
     * @param page
     * @param condition
     * @return
     */
    private ResultBean getAirPage(Pageable page, CenterMajorHazardSearchBean condition) {
        QMhMonitoringPoint point = QMhMonitoringPoint.mhMonitoringPoint;
        Predicate p = null;
        if (condition.getName() != null) {
            p = ExpressionUtils.and(p, point.name.contains(condition.getName()));
        }
        p = ExpressionUtils.and(p,
                ExpressionUtils.or(point.showState.eq(DataStateTypes.EFFECTIVE.getState()), point.showState.isNull()));
        p = ExpressionUtils.and(p, point.mhMonitoringType.in(mhMonitoringTypeDao.findByCategoryIdAndCode(1L, condition.getPointTypeCode())));
        Page<MhMonitoringPoint> pageData = p == null ? monitoringPointDao.findAll(page) : monitoringPointDao.findAll(p, page);
        Page<AirMonitoringBean> beanPage = getAirBeanPage(pageData);
        return ResultBean.pageData(beanPage.getContent(), beanPage.getTotalElements());
    }

    private Page<AirMonitoringBean> getAirBeanPage(Page<MhMonitoringPoint> pageData) {
        return PageDataUtils.convertPageData(pageData, new PageDataUtils.PageDataConvert<AirMonitoringBean, MhMonitoringPoint>() {
            @Override
            public AirMonitoringBean convert(MhMonitoringPoint point) {
                return convertAir(point);
            }
        });
    }

    private ResultBean getFacilityPage(Pageable page, CenterMajorHazardSearchBean condition) {
        List<FacilityMonitoringBean> list = new ArrayList<>();
        List<BpDeviceFacilityCollection> facilities = getFacilitieList(page.getPageNumber(), page.getPageSize(), 1);
//        String orgCode = Context.getCurrentOrgCode().substring(0, 7);
        String orgCode = Context.getCompanyCode();
        int number = 0;
        if (condition.getName() != null) {
//            Optional<BpDeviceFacilityCollection> bpDeviceFacilityCollection = IntStream.range(0, facilities.size()).filter(i ->
//                    !facilities.get(i).getName().contains(condition.getName())).
//                    boxed().findFirst().map(i -> facilities.remove((int) i));
            number = bpDeviceFacilityCollectionDao.countNumberByName(orgCode, condition.getName());
        } else {
            number = bpDeviceFacilityCollectionDao.countNumber(orgCode);
        }
        if (!CollectionUtils.isEmpty(facilities)) {
            for (BpDeviceFacilityCollection f : facilities) {
                if ("独立库区".equals(f.getName()) && DeviceFacilityTypes.KU_QU.getName().equals(f.getDeviceTypeName())
                        || DeviceFacilityTypes.GONG_YI_LIU_CHENG.getName().equals(f.getDeviceTypeName())) {
                    // 忽略独立库区和工艺流程
                    number = number - 1;
                } else {
                    if (condition.getName() == null) {
                        list.add(convert(f));
                    } else {
                        if (f.getName().contains(condition.getName())) {
                            list.add(convert(f));
                        }
                    }
                }
            }
            sortFacilities(list);
        }
        return ResultBean.pageData(list, number);
    }

    /**
     * 大屏-重大危险源监测预警列表-重大危险源
     *
     * @param page
     * @param condition
     * @return
     */
    private ResultBean getMajorHazardPage(Pageable page, CenterMajorHazardSearchBean condition) {
        page = PageDataUtils.addOrderByAsc(page, "level");
        QMhMajorHazard hazard = QMhMajorHazard.mhMajorHazard;
        Predicate p = null;
        if (condition.getName() != null) {
            p = ExpressionUtils.and(p, hazard.name.contains(condition.getName()));
        }
        p = ExpressionUtils.and(p, ExpressionUtils.or(hazard.state.notIn(DataStateTypes.DELETE.getState()),
                hazard.state.isNull()));
        Page<MhMajorHazard> pageData = p == null ? majorHazardDao.findAll(page) : majorHazardDao.findAll(p, page);
        Page<MajorHazardMonitoringBean> beanPage = getMajorHazardBeanPage(pageData);
        //排序 Index
        List<MajorHazardMonitoringBean> dataList = beanPage.getContent();
        if (!CollectionUtils.isEmpty(dataList)) {
            dataList = dataList.stream().sorted(Comparator.comparing(MajorHazardMonitoringBean::getIndex).thenComparing(MajorHazardMonitoringBean::getIndex)).collect(Collectors.toList());
        }
        return ResultBean.pageData(dataList, beanPage.getTotalElements());
    }

    private Page<MajorHazardMonitoringBean> getMajorHazardBeanPage(Page<MhMajorHazard> pageData) {
        return PageDataUtils.convertPageData(pageData, new PageDataUtils.PageDataConvert<MajorHazardMonitoringBean, MhMajorHazard>() {
            @Override
            public MajorHazardMonitoringBean convert(MhMajorHazard majorHazard) {
                return convertMa(majorHazard);
            }
        });
    }

    private Page<DistrictInfoBean> getCenterRiskDistrictBeanPage(Page<RiskDistrict> pageData) {
        return PageDataUtils.convertPageData(pageData, new PageDataUtils.PageDataConvert<DistrictInfoBean, RiskDistrict>() {
            @Override
            public DistrictInfoBean convert(RiskDistrict riskDistrict) {
                DistrictInfoBean bean = convertToDistrictInfoBean(riskDistrict);
                int count = bpWorkSafetyCertDao.countByRiskDistrickId(bean.getId());
                bean.setWorkCount(count);
                return bean;
            }
        });
    }

    //设备设危险源
    private String findMajorHazardInfoOfDevice(BpDeviceFacilityCollection device) {
        DeviceFacilityTypes type = DeviceFacilityTypes.findByName(device.getDeviceTypeName());
        if (type == DeviceFacilityTypes.SHENG_CHAN_ZHUANG_ZHI) {
            Optional<BpProductionFacility> bpf = facilityDao.findById(device.getDeviceId());
            if (bpf.isPresent()) {
                return getMajorHazardName(bpf.get().getMajorHazardId());
            }
        } else if (type == DeviceFacilityTypes.CHU_GUAN) {
            BpStorageTank tank = storageTankDao.findById(device.getDeviceId()).orElse(null);
            if (tank != null && tank.getMhMajorHazard() != null) {
                return tank.getMhMajorHazard().getName();
            }
        } else if (type == DeviceFacilityTypes.CHU_GUAN_QU) {
            BpStorageTankArea tank = storageTankAreaDao.findById(device.getDeviceId()).orElse(null);
            if (tank != null && tank.getMhMajorHazard() != null) {
                return tank.getMhMajorHazard().getName();
            }
        } else if (type == DeviceFacilityTypes.GONG_YE_GUAN_DAO) {
            // BpIndustrialPipeline line = industrialPipelineDao.findById(device.getDeviceId()).orElse(null);
            // if(line!=null && line.get)
        } else if (type == DeviceFacilityTypes.KU_FANG) {
            BpStoreHouse house = storeHouseDao.findById(device.getDeviceId()).orElse(null);
            if (house != null && house.getMajorHazardId() != null) {
                return majorHazardDao.getOne(house.getMajorHazardId()).getName();
            }
        } else if (type == DeviceFacilityTypes.KU_QU) {
            BpStoreArea house = storeAreaDao.findById(device.getDeviceId()).orElse(null);
            if (house != null && house.getMajorHazardId() != null) {
                return majorHazardDao.getOne(house.getMajorHazardId()).getName();
            }
        }
        return "";
    }

    private String getMajorHazardName(Long majorHazardId) {
        if (majorHazardId != null) {
            Optional<MhMajorHazard> hazardById = majorHazardDao.findById(majorHazardId);
            if (hazardById.isPresent()) {
                return hazardById.get().getName();
            } else {
                return "";
            }
        } else {
            return "";
        }
    }

    //监测点
    private List<MonitoringPointValueBean> convertMonitoringPointsValue(List<BpDeviceFacilityMonitoringPoint> mhMonitoringPoints) {
        List<MonitoringPointValueBean> list = new ArrayList<>();
        for (BpDeviceFacilityMonitoringPoint mp : mhMonitoringPoints) {
            Optional<MhMonitoringPoint> omp = monitoringPointDao.findById(mp.getMonitoringPointId());
            if (omp.isPresent()) {
                list.add(getMonitoringPointValueBean(omp.get()));
            }
        }
        return list;
    }

    private MonitoringPointValueBean getMonitoringPointValueBean(MhMonitoringPoint p) {
        MonitoringPointValueBean b = new MonitoringPointValueBean();
        //监测点显示状态为0,跳过
        if (p.getShowState() != null && p.getShowState() == 0) {
            return null;
        }

        b.setId(p.getId());
        b.setPointName(p.getName());
        if (p.getMhMonitoringType() != null) {
            b.setType(p.getMhMonitoringType().getName());
        }
        //状态 0正常,1,异常,2未连接
        MhValueAndStateBean switchState = getSwitchState(p);
        Integer state = switchState.getState();
        if (state != null && state == 0) {
            Double val = mhMonitoringPointService.realTimeVal(p);
            b.setValue(this.getPointValueByTypeUnits(p, val));
        } else if (state != null && state == 2) {
            b.setValue("未连接");
        }
        Integer flag = getAlarmFlag(p);
        if (flag == 1) {
            state = 1;
        }
        b.setStatus(state);
        return b;
    }

    private String getPointValueByTypeUnits(MhMonitoringPoint p, Double val) {
        String value;
        if (val != null) {
            if (p.getMhMonitoringType() != null && StringUtils.isNotBlank(p.getMhMonitoringType().getDefaultType()) &&
                    p.getMhMonitoringType().getDefaultType().equals("Y")) {
                value = mhMonitoringRealTimeService.getVauleByPointsUnits(p, val.toString());
            } else {
                value = NumberUtils.keepDigits(val, 2);
            }
        } else {
            value = "已连接,暂无实时数据";
        }
        return value;
    }

    //危险源排序
    private void sortDanderList(List<MajorHazardMonitoringBean> dangerList) {
        if (dangerList == null) {
            return;
        }
        Collections.sort(dangerList, new Comparator<MajorHazardMonitoringBean>() {

            @Override
            public int compare(MajorHazardMonitoringBean o1, MajorHazardMonitoringBean o2) {
                return getDangerLevel(o1) - getDangerLevel(o2);
            }
        });
    }

    //危险源等级
    protected int getDangerLevel(MajorHazardMonitoringBean o1) {
        if ("一级".equals(o1.getLevel())) {
            return 1;
        } else if ("二级".equals(o1.getLevel())) {
            return 2;
        } else if ("三级".equals(o1.getLevel())) {
            return 3;
        } else if ("四级".equals(o1.getLevel())) {
            return 4;
        } else if ("五级".equals(o1.getLevel())) {
            // 实际只到4级，多谢一些，防止有变化
            return 5;
        } else if ("六级".equals(o1.getLevel())) {
            return 6;
        } else if ("七级".equals(o1.getLevel())) {
            return 7;
        }
        return 100;
    }

    //危险源信息
    private MajorHazardMonitoringBean convertMa(MhMajorHazard mh) {
        MajorHazardMonitoringBean mb = new MajorHazardMonitoringBean();
        mb.setArea(mh.getName());
        mb.setId(mh.getId());
        mb.setLevel(mh.getLevel());
        if (StringUtils.isBlank(mh.getLevel())) {
            mb.setIndex(10000);
        }
        if (mh.getLevel().equals("一级")) {
            mb.setIndex(1);
        } else if (mh.getLevel().equals("二级")) {
            mb.setIndex(2);
        } else if (mh.getLevel().equals("三级")) {
            mb.setIndex(3);
        } else if (mh.getLevel().equals("四级")) {
            mb.setIndex(4);
        } else if (mh.getLevel().equals("非重大")) {
            mb.setIndex(5);
        } else {
            // 未匹配的level, index默认99, 防止排序报错
            mb.setIndex(99);
        }
        mb.setName(mh.getName());

        //获取设备列表
        int flag = 0;
        int count = mhAlarmMessageDao.countMhNumber(mh.getId(), 0);
        if (count > 0) {
            flag = 1;
        }
        if (flag == 0) {
            //正常
            mb.setStatus(0);
        } else {
            //异常
            mb.setStatus(1);
        }
        parseMhCoordinates(mh, mb);
        return mb;
    }

    //监测点连接状态:0连接,1未连接
    private MhValueAndStateBean getSwitchState(MhMonitoringPoint p) {
        MhValueAndStateBean bean = new MhValueAndStateBean();
        Integer state = null;
        if (p.getState() != null && p.getState() == 1) {
            if (p.getSwitchs() != null) {
                if (p.getSwitchs().equals("1")) {
                    state = 0;
                    bean.setRealTimeValue(1.0);
                }
                if (p.getSwitchs().equals("0")) {
                    state = 0;
                    bean.setRealTimeValue(0.0);
                }
            } else {
                MonitorPointData realTimeValue = monitorPointDataService
                        .realTimeVal(Context.getCurrentTenantId(), Context.getCompanyCode(),
                                p.getPointCode())
                        .orElse(null);
                if (realTimeValue == null) {
                    state = 2;
                } else {
                    bean.setRealTimeValue(realTimeValue.getValue());
                    state = 0;
                }
            }
        } else {
            state = 2;
            if (p.getSwitchs() != null) {
                bean.setRealTimeValue(0.0);
            }
        }
        if ("联锁投切".equals(p.getMhMonitoringType().getName()) || "运行状态".equals(p.getMhMonitoringType().getName())) {
            bean.setRealTimeValue(null);
        }
        bean.setState(state);
        return bean;
    }


    //危险源位置
    private void parseMhCoordinates(MhMajorHazard mh, MajorHazardMonitoringBean mb) {
        String location = mh.getLocation();
        MapUtils.WwytPoint point = MapUtils.parseSinglePoint(location);
        // Point point = MapUtils.parseCoordinate(location);
        if (point != null && point.getX() != null && point.getY() != null) {
            mb.setX(point.getX());
            mb.setY(point.getY());
            mb.setZ(point.getZ() == null ? 0.00 : point.getZ());
            mb.setFloorId(point.getFloorId());
            mb.setLocation(location);
        }
    }

    //有毒可燃气体
    private AirMonitoringBean convertAir(MhMonitoringPoint p) {
        AirMonitoringBean fb = new AirMonitoringBean();
        fb.setName(p.getName());
        fb.setId(p.getId());
        //状态 0正常,1,异常,2未连接
        MhValueAndStateBean switchState = getSwitchState(p);
        Integer state = switchState.getState();
        return this.createAirBean(p, fb, state, null);
    }

    //是否报警flag 0不报警;1报警
    private Integer getAlarmFlag(MhMonitoringPoint p) {
        int flag = 0;
        int count = mhAlarmMessageDao.countByMhPointIdAndStateNotEq(p.getId(), 2);
        if (count > 0) {
            flag = 1;
        }
        return flag;
    }

    //优化后
    private Integer getAlarmFlagYou(int count) {
        int flag = 0;
//        int count = mhAlarmMessageDao.countByMhPointIdAndStateNotEq(p.getId(), 2);
        if (count > 0) {
            flag = 1;
        }
        return flag;
    }

    //设备设施
    private FacilityMonitoringBean convert(BpDeviceFacilityCollection f) {
        FacilityMonitoringBean fb = new FacilityMonitoringBean();
        fb.setCode(f.getCode());
        fb.setArea(f.getDistrictName());
        fb.setName(f.getName());
        fb.setId(f.getId());
        fb.setDeviceId(f.getDeviceId());
        fb.setLocation(f.getCoordinates());
        int flag = 0;
        //      获取设备和监测点的关联列表-危险源有关的监测点
        List<BpDeviceFacilityMonitoringPoint> dpList = bpDeviceFacilityMonitoringPointDao.findByDeviceId(f.getId());
        if (!CollectionUtils.isEmpty(dpList)) {
            for (BpDeviceFacilityMonitoringPoint dp : dpList) {
                //获取监测点的报警信息
                int i = mhAlarmMessageDao.countByMhPointIdAndStateNotEq(dp.getMonitoringPointId(), 2);
                if (i > 0) {
                    flag = 1;
                    break;
                }
            }
        }

//        int i = mhAlarmMessageDao.countByDeviceIdIdAndStateNotEq(f.getId(), 2);
        if (flag == 0) {
            //正常
            fb.setStatus(0);
        } else {
            //异常
            fb.setStatus(1);
        }

        fb.setType(f.getDeviceTypeName());
        fb.setBindMonitorPointCount(
                bpDeviceFacilityMonitoringPointDao.findBindMonitoringPointCountOfDevice(f.getId()).intValue());
        if (DeviceFacilityTypes.SHENG_CHAN_ZHUANG_ZHI.getName().equals(f.getDeviceTypeName())) {
            fb.setDepartName(facilityDao.findDepartNameById(f.getDeviceId()));
        }
        if (DeviceFacilityTypes.CHU_GUAN_QU.getName().equals(f.getDeviceTypeName())) {
            Gson gson = new Gson();
            try {
                MapUtils.SafetyPoints points = gson.fromJson(f.getCoordinates(), MapUtils.SafetyPoints.class);
                List<MapUtils.SafetyPoint> safetyPoints = points.getPoints();
                MapUtils.SafetyPoint point = MapUtils.calculateCenterPointZ(safetyPoints);
                fb.setFloorId(points.getFloorId().toString());
                fb.setX(point.getX());
                fb.setY(point.getY());
                fb.setZ(point.getZ());
                return fb;
            } catch (Exception e) {

            }
        }
        MapUtils.WwytPoint point = MapUtils.parseSinglePoint(f.getCoordinates());
        if (point != null && point.getX() != null && point.getY() != null) {
            fb.setX(point.getX());
            fb.setY(point.getY());
            fb.setZ(point.getZ() == null ? 0.00 : point.getZ());
            fb.setFloorId(String.valueOf(point.getFloorId()));
        } else {
            MapUtils.SafetyPoints points = MapUtils.parse3DSafetyPointsFromJson(f.getCoordinates());
            if (points != null && cn.zlg.common.util.CollectionUtils.isNotEmpty(points.getPoints())) {
                MapUtils.SafetyPoint point2 = MapUtils.calculateCenterPointZ(points.getPoints());
                fb.setX(point2.getX());
                fb.setY(point2.getY());
                fb.setZ(point2.getZ() == null ? 0.00 : point2.getZ());
                fb.setFloorId(String.valueOf(points.getFloorId()));
            }
        }
        return fb;
    }


    //生产装置排序
    private void sortFacilities(List<FacilityMonitoringBean> facilityList) {
        if (facilityList == null) {
            return;
        }
        Collections.sort(facilityList, new Comparator<FacilityMonitoringBean>() {

            // 2019年12月27日13:00:25再次调整
            // 第一顺位，有监测点的：
            // 生产装置
            // 储罐区
            // 储罐
            // 库房
            // 库区
            // 第二顺位，无监测点的：
            // 生产装置
            // 储罐区
            // 储罐
            // 库房
            // 库区
            @Override
            public int compare(FacilityMonitoringBean o1, FacilityMonitoringBean o2) {
                int point1 = calculatePoint(o1);
                int point2 = calculatePoint(o2);
                // 分数大的显示在前
                return point2 - point1;
            }

            private int calculatePoint(FacilityMonitoringBean o1) {
                int base = 0;
                if (o1.getBindMonitorPointCount() > 0) {
                    base = 1000;
                }
                if (DeviceFacilityTypes.CHU_GUAN_QU.getName().equals(o1.getType())) {
                    base += 100;
                } else if (DeviceFacilityTypes.KU_FANG.getName().equals(o1.getType())) {
                    base += 80;
                } else if (DeviceFacilityTypes.CHU_GUAN.getName().equals(o1.getType())) {
                    base += 90;
                } else if (DeviceFacilityTypes.KU_QU.getName().equals(o1.getType())) {
                    base += 70;
                } else if (DeviceFacilityTypes.SHENG_CHAN_ZHUANG_ZHI.getName().equals(o1.getType())) {
                    base += 110;
                }
                return base;
            }
        });
    }

    //监控探头
    private List<CameraMonitoringBean> findAllCameras() {
        List<BpSystemVideo> list = bpSystemVideoDao.findAll();
        List<CameraMonitoringBean> re = new ArrayList<>();
        //优化
        if (!CollectionUtils.isEmpty(list)) {
            List<String> names = list.stream().filter(b -> StringUtils.isNotBlank(b.getName())).map(BpSystemVideo::getName).collect(Collectors.toList());
            List<AlarmMessageCountBean> countBeans = alarmMessageService.findCameraAlarms(names, Context.getCurrentTenantId(), Context.getCurrentOrgCode());
            Map<String, Integer> countMap = CollectionUtil.isNotEmpty(countBeans) ?
                    countBeans.stream().collect(Collectors.toMap(AlarmMessageCountBean::getName, AlarmMessageCountBean::getCountNum))
                    : new HashMap<>();
            for (BpSystemVideo sv : list) {
                re.add(convertCamerasBean(sv, countMap));
            }
        }
        return re;
    }

    private CameraMonitoringBean convertCamerasBean(BpSystemVideo sv, Map<String, Integer> countMap) {
        int count;
        if (countMap != null && StringUtils.isNotBlank(sv.getName())) {
            if (countMap.get(sv.getName()) == null) {
                count = 0;
            } else {
                count = countMap.get(sv.getName());
            }
        } else {
            count = findCameraAlarm(sv.getName(), Context.getCurrentTenantId(), Context.getCurrentOrgCode());
        }
        CameraMonitoringBean c = new CameraMonitoringBean();
        c.setId(sv.getId());
        // c.setArea(sv.getName());
        c.setName(sv.getName());
        c.setRtmp(sv.getRealTimeSite());
        //c.setStatus(0);
        ThreeDPoints threeDPoints = MapUtils.parse3DPointsFromJson(sv.getRegion());
        Gson gson = new Gson();
        MapUtils.SafetyPoints points = null;
        try {
            points = gson.fromJson(sv.getRegion(), MapUtils.SafetyPoints.class);
        } catch (Exception e) {
            log.error("位置点位转换错误");
            e.printStackTrace();
        }
        if (points != null) {
            List<MapUtils.SafetyPoint> safetyPoints = points.getPoints();
            MapUtils.SafetyPoint point = MapUtils.calculateCenterPointZ(safetyPoints);
            c.setX(point.getX());
            c.setY(point.getY());
            c.setZ(point.getZ() == null ? 0.00 : point.getZ());
            c.setFloorId(String.valueOf(threeDPoints.getFloorId()));
        } else {
            MapUtils.WwytPoint point = MapUtils.parseSinglePoint(sv.getRegion());
            if (point != null && point.getX() != null && point.getY() != null) {
                c.setX(point.getX());
                c.setY(point.getY());
                c.setZ(point.getZ() == null ? 0.00 : point.getZ());
            }
        }
        //设置摄像头的状态,默认正常
        c.setStatus(0);
        if (StringUtils.isNotBlank(sv.getName())) {
            if (count > 0) {
                c.setStatus(1);
            }
        }
        return c;
    }

    private int findCameraAlarm(String cameraName, Long tenentId, String orgCode) {
        return alarmMessageService.findCameraAlarm(cameraName, tenentId, orgCode);
    }

    @Override
    public List<NewAlarmMessage> findNewAlarmMessage() {
        BaseConfig config = baseConfigService.findConfig(Context.getCurrentTenantId(), Context.getCompanyCode(),
                BaseConfigCodes.ALARM_MESSAGE_TIME_LINE);
        Date timeline = findTimeLine(config);
        List<MhAlarmMessage> mh = mhAlarmMessageDao.findByCreateTimeAfter(DateTimeUtil.date2LocalDateTime(timeline));
        List<RiskEvaluationAlarmMesage> risk = riskEvaluationAlarmMesageDao.findByCreateTimeAfter(timeline);
        List<McAlarmMessageBean> alarmMessages = findLocateMessagesAfter(timeline);
        List<NewAlarmMessage> merge = merge(mh, risk, alarmMessages);
        if (merge.size() > 0) {
            String newTimeLine = merge.get(0).getTime();
            config.setValue(newTimeLine);
            //BaseConfigBean baseConfigBean = new BaseConfigBean();
            baseConfigService.updateConfig(config);
        }
        return merge;
    }

    private List<McAlarmMessageBean> findLocateMessagesAfter(Date timeline) {
        List<McAlarmMessageBean> messages = localteServerService.alarmMessages();
        String timeString = SimpleDateFormatCache.getYmdhms().format(timeline);
        List<McAlarmMessageBean> re = new ArrayList<>(messages.size());
        for (McAlarmMessageBean b : messages) {
            if (b.getTime() != null && b.getTime().compareTo(timeString) > 0) {
                re.add(b);
            }
        }
        return re;
    }

    private Date findTimeLine(BaseConfig config) {
        if (config == null) {
            config = baseConfigService.addConfig(BaseConfigCodes.ALARM_MESSAGE_TIME_LINE,
                    SimpleDateFormatCache.getYmdhms().format(new Date()));
        }
        try {
            return SimpleDateFormatCache.getYmdhms().parse(config.getValue());
        } catch (ParseException e) {
        }
        return new Date();
    }

    private List<NewAlarmMessage> merge(List<MhAlarmMessage> mh, List<RiskEvaluationAlarmMesage> risk,
                                        List<McAlarmMessageBean> alarmMessages) {
        List<NewAlarmMessage> list = new ArrayList<>(mh.size() + risk.size() + alarmMessages.size());
        for (MhAlarmMessage m : mh) {
            list.add(convert(m));
        }
        for (RiskEvaluationAlarmMesage m : risk) {
            list.add(convert(m));
        }
        for (McAlarmMessageBean m : alarmMessages) {
            list.add(convert(m));
        }
        if (list.size() > 0) {
            Collections.sort(list, new Comparator<NewAlarmMessage>() {

                @Override
                public int compare(NewAlarmMessage o1, NewAlarmMessage o2) {
                    return o2.getTime().compareTo(o1.getTime());
                }
            });
        }
        return list;
    }

    private NewAlarmMessage convert(McAlarmMessageBean m) {
        NewAlarmMessage bean = new NewAlarmMessage();
        bean.setId(m.getId());
        bean.setModule("人员在岗在位");
        bean.setTime(m.getTime());
        return bean;
    }

    private NewAlarmMessage convert(MhAlarmMessage m) {
        NewAlarmMessage bean = new NewAlarmMessage();
        bean.setId(m.getId());
        bean.setModule("重大危险源");
        bean.setTime(SimpleDateFormatCache.getYmdhms().format(DateTimeUtil.localDateTime2Date(m.getCreateTime())));
        return bean;
    }

    private NewAlarmMessage convert(RiskEvaluationAlarmMesage m) {
        NewAlarmMessage bean = new NewAlarmMessage();
        bean.setId(m.getId());
        bean.setModule("风险分区");
        bean.setTime(SimpleDateFormatCache.getYmdhms().format(m.getCreateTime()));
        return bean;
    }

}

